Site icon TestingDocs.com

MySQL SELECT WHERE Clause

Overview

In this tutorial, we will learn MySQL SELECT WHERE clause with examples. The WHERE clause is the mechanism for selecting the rows that we want in the query result set. We can filter rows by looking for column values that satisfy some condition criteria specified in the WHERE clause.

Syntax

Simple syntax of the WHERE clause in the SELECT query is shown below:

mysql>SELECT column_list FROM <table_name>
             WHERE  <condition /expression(s)> ;

 

We can use the following types of operators in expressions in the WHERE clause:

 

Operators Description
Arithmetic Operators Operators used for arithmetic calculations
Comparison Operators Operators used for comparison of one expression with another expression
Logical Operators Operators used to combine different WHERE conditions

 

Examples

In this example, we will use the City table from the world MySQL database. The table format and the columns ca be found using the following command:

mysql> DESC City;
+————-+———-+——+—–+———+—————-+
| Field | Type | Null | Key | Default | Extra |
+————-+———-+——+—–+———+—————-+
| ID | int | NO | PRI | NULL | auto_increment |
| Name | char(35) | NO | | | |
| CountryCode | char(3) | NO | MUL | | |
| District | char(20) | NO | | | |
| Population | int | NO | | 0 | |
+————-+———-+——+—–+———+—————-+
5 rows in set (0.00 sec)

 

The table contains many rows. To know the row count, execute the following query:

mysql> SELECT COUNT(*) FROM City;
+———-+
| COUNT(*) |
+———-+
| 4079 |
+———-+
1 row in set (0.00 sec)

 

We can use the WHERE clause to filter the rows. For example, we are interested to know the Population of the city New York. We will use the Equal To operator to build the WHERE condition.

WHERE Name = ‘New York’

Name is a string of character data type column. We need to enclose the string New York in ‘  ‘ characters.

 

mysql> SELECT * FROM City WHERE Name=’New York’;
+——+———-+————-+———-+————+
| ID | Name | CountryCode | District | Population |
+——+———-+————-+———-+————+
| 3793 | New York | USA | New York    | 8008278   |
+——+———-+————-+———-+————+
1 row in set (0.00 sec)

The * returns all the columns in the table. We can filter the columns by specifying the column names in the SELECT query.

mysql> SELECT Population FROM City WHERE Name=’New York’;

MySQL Tutorials

MySQL Tutorials on this website:

https://www.testingdocs.com/mysql-tutorials-for-beginners/

For more information on MySQL Database:

https://www.mysql.com/

Exit mobile version