If you are interested to learn about the MySQL SQL
The MySQL SELECT Statement
The SELECT
statement is used to select data from a database. The data returned is stored in a result table, called the result-set.
SELECT Syntax
SELECT column1, column2, ...
FROM table_name;
Here, column1, column2, … are the field names of the table you want to select data from. If you want to select all the fields available in the table, use the following syntax:
SELECT * FROM table_name;
For example: SELECT order_id, quantity, unit_price FROM order_details WHERE quantity < 500 ORDER BY quantity ASC, unit_price DESC; This MySQL SELECT example would return only the order_id, quantity, and unit_price fields from the order_details table where the quantity is less than 500.
How do I write a select statement in MySQL?
First, specify one or more columns from which you want to select data after the SELECT keyword. If the select_list has multiple columns, you need to separate them by a comma ( , ). Second, specify the name of the table from which you want to select data after the FROM keyword.
Demo Database
In this tutorial we will use the well-known Northwind sample database. Below is a selection from the “Customers” table in the Northwind sample database:
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 |
SELECT Columns Example
The following SQL statement selects the “CustomerName”, “City”, and “Country” columns from the “Customers” table:
Example
SELECT CustomerName, City, Country FROM Customers;
SELECT * Example
The following SQL statement selects ALL the columns from the “Customers” table:
Example
SELECT * FROM Customers;
The MySQL SELECT DISTINCT Statement
The SELECT DISTINCT
statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.
SELECT DISTINCT Syntax
SELECT DISTINCT column1, column2, ...
FROM table_name;
SELECT Example Without DISTINCT
The following SQL statement selects all (including the duplicates) values from the “Country” column in the “Customers” table:
Example
SELECT Country FROM Customers;
Now, let us use the SELECT DISTINCT
statement and see the result.
SELECT DISTINCT Examples
The following SQL statement selects only the DISTINCT values from the “Country” column in the “Customers” table:
Example
SELECT DISTINCT Country FROM Customers;
The following SQL statement counts and returns the number of different (distinct) countries in the “Customers” table:
Example
SELECT COUNT(DISTINCT Country) FROM Customers;
The MySQL WHERE Clause
The WHERE
clause is used to filter records. It is used to extract only those records that fulfill a specified condition. The WHERE clause works like an if condition in any programming language. This clause is used to compare the given value with the field value available in a MySQL table. If the given value from outside is equal to the available field value in the MySQL table, then it returns that row.
WHERE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Demo Database
Below is a selection from the “Customers” table in the Northwind sample database:
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 |
WHERE Clause Example
The following SQL statement selects all the customers from “Mexico”:
Example
SELECT * FROM Customers WHERE Country = 'Mexico';
Text Fields vs. Numeric Fields
SQL requires single quotes around text values (most database systems will also allow double quotes). However, numeric fields should not be enclosed in quotes:
Example
SELECT * FROM Customers WHERE CustomerID = 1;
Operators in The WHERE Clause
The following operators can be used in the WHERE
clause:
Operator | Description | Example |
---|---|---|
= | Equal | Try it |
> | Greater than | Try it |
< | Less than | Try it |
>= | Greater than or equal | Try it |
<= | Less than or equal | Try it |
<> | Not equal. Note: In some versions of SQL this operator may be written as != | Try it |
BETWEEN | Between a certain range | Try it |
LIKE | Search for a pattern | Try it |
IN | To specify multiple possible values for a column |
Fetching Data from the Command Prompt
Example
The following example will return all the records from the tutorials_tbl table for which the author name is Sanjay.
root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from tutorials_tbl WHERE tutorial_author = 'Sanjay'; +-------------+----------------+-----------------+-----------------+ | tutorial_id | tutorial_title | tutorial_author | submission_date | +-------------+----------------+-----------------+-----------------+ | 3 | JAVA Tutorial | Sanjay | 2007-05-21 | +-------------+----------------+-----------------+-----------------+ 1 rows in set (0.01 sec) mysql>
Unless performing a LIKE comparison on a string, the comparison is not case sensitive. You can make your search case sensitive by using the BINARY keyword as follows −
root@host# mysql -u root -p password; Enter password:******* mysql> use TUTORIALS; Database changed mysql> SELECT * from tutorials_tbl \ WHERE BINARY tutorial_author = 'sanjay'; Empty set (0.02 sec) mysql>
Fetching Data Using a PHP Script
PHP uses mysqli query() or mysql_query() function to select records in a MySQL table using where clause. This function takes two parameters and returns TRUE on success or FALSE on failure.
Syntax
$mysqli->query($sql,$resultmode)
Sr.No. | Parameter & Description |
---|---|
1 | $sqlRequired – SQL query to select records in a MySQL table using Where Clause. |
2 | $resultmodeOptional – Either the constant MYSQLI_USE_RESULT or MYSQLI_STORE_RESULT depending on the desired behavior. By default, MYSQLI_STORE_RESULT is used. |
Example
Try the following example to select a record using where clause in a table −
<html> <head> <title>Using Where Clause</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root@123'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); if($mysqli->connect_errno ) { printf("Connect failed: %s<br />", $mysqli->connect_error); exit(); } printf('Connected successfully.<br />'); $sql = 'SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl where tutorial_author = "Mahesh"'; $result = $mysqli->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_assoc()) { printf("Id: %s, Title: %s, Author: %s, Date: %d <br />", $row["tutorial_id"], $row["tutorial_title"], $row["tutorial_author"], $row["submission_date"]); } } else { printf('No record found.<br />'); } mysqli_free_result($result); $mysqli->close(); ?> </body> </html>
Output
Access the mysql_example.php deployed on apache web server and verify the output. Here we’ve entered multiple records in the table before running the select script.
Connected successfully.
Id: 1, Title: MySQL Tutorial, Author: Mahesh, Date: 2021
Id: 2, Title: HTML Tutorial, Author: Mahesh, Date: 2021
Id: 3, Title: PHP Tutorial, Author: Mahesh, Date: 2021