MySQL SELECT Statement
The SELECT statement in MySQL is used to fetch data from one or more tables. We can retrieve records of all fields or specified fields that match specified criteria using this statement. It can also work with various scripting languages such as PHP, Ruby, and many more.
SELECT Statement Syntax
It is the most commonly used SQL query. The general syntax of this statement to fetch data from tables are as follows:
Syntax for all fields:
The SELECT statement uses the following parameters:
NOTE: It is to note that MySQL always evaluates the FROM clause first, and then the SELECT clause will be evaluated.
MySQL SELECT Statement Example:
Let us understand how SELECT command works in MySQL with the help of various examples. Suppose we have a table named employee_detail that contains the following data:
1. If we want to retrieve a single column from the table, we need to execute the below query:
We will get the below output where we can see only one column records.
2. If we want to query multiple columns from the table, we need to execute the below query:
We will get the below output where we can see the name, email, and city of employees.
3. If we want to fetch data from all columns of the table, we need to use all column's names with the select statement. Specifying all column names is not convenient to the user, so MySQL uses an asterisk (*) to retrieve all column data as follows:
We will get the below output where we can see all columns of the table.
4. Here, we use the SUM function with the HAVING clause in the SELECT command to get the employee name, city, and total working hours. Also, it uses the GROUP BY clause to group them by the Name column.
It will give the below output:
5. MySQL SELECT statement can also be used to retrieve records from multiple tables by using a JOIN statement. Suppose we have a table named "customer" and "orders" that contains the following data:
Execute the following SQL statement that returns the matching records from both tables using the INNER JOIN query:
After successful execution of the query, we will get the output as follows: