MySQL SELECT Statement

Understanding the MySQL SELECT Statement

The SELECT statement is one of the most fundamental commands in SQL, allowing users to retrieve specific data from a database. It is widely used to query and extract meaningful information from relational databases.

What Does the SELECT Statement Do?

The SELECT statement:

  • Retrieves data from one or more columns in a database table.
  • Returns the data in the form of a result-set, which is essentially a table of rows and columns.

Syntax of the SELECT Statement

To select specific columns:

SELECT column1, column2, ...
FROM table_name;

To select all columns:

SELECT * FROM table_name;

Explanation

  • SELECT: Specifies the fields (columns) to retrieve.
  • *: A wildcard symbol that retrieves all columns.
  • FROM table_name: Indicates the table from which the data is to be retrieved.

Demo Database: Northwind

The following examples use the well-known Northwind sample database, which contains tables such as "Customers," "Orders," and "Products."

Below is a sample selection from the "Customers" table:

CustomerID CustomerName ContactName Address City PostalCode Country
1 Alfreds Futterkiste Maria Anders Obere Str. 57 Berlin 12209 Germany
2 Ana Trujillo Emparedados y helados Ana Trujillo Avda. de la Constitución 2222 México D.F. 05021 Mexico
3 Antonio Moreno Taquería Antonio Moreno Mataderos 2312 México D.F. 05023 Mexico
4 Around the Horn Thomas Hardy 120 Hanover Sq. London WA1 1DP UK
5 Berglunds snabbköp Christina Berglund Berguvsvägen 8 Luleå S-958 22 Sweden

Examples of the SELECT Statement

Selecting Specific Columns

If you want to retrieve specific fields such as CustomerName, City, and Country from the "Customers" table, use this query:

SELECT CustomerName, City, Country FROM Customers;

Result:

CustomerName City Country
Alfreds Futterkiste Berlin Germany
Ana Trujillo Emparedados y helados México D.F. Mexico
Antonio Moreno Taquería México D.F. Mexico
Around the Horn London UK
Berglunds snabbköp Luleå Sweden

Selecting All Columns

To retrieve all the fields from the "Customers" table, use the wildcard *:

SELECT * FROM Customers;

Result:

This will return all columns and rows from the "Customers" table, as shown in the sample data above.


Key Points to Remember

  1. Use Specific Columns for Efficiency: Querying specific columns improves performance, especially for large datasets.
  2. Case-Insensitive Keywords: SQL keywords like SELECT and FROM are not case-sensitive, but conventionally written in uppercase.
  3. Using the Wildcard *: Retrieve all columns when needed, but avoid using it if only specific data is required.
  4. Semicolon: Some database systems require a semicolon (;) at the end of the statement, which is a good practice to follow.

By mastering the SELECT statement, you unlock the power to query and analyze data efficiently from relational databases like MySQL.


Was this article helpful?