The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.
If you want to select a subset of rows from a table, you use the WHERE clause in your SELECT statement.
SELECT column1, column2, ... FROM table_name WHERE condition;
Below is a selection from the Customers table used in the examples:
Customers Table:
| CustomerID | CustomerName | City | Country |
|---|---|---|---|
| 1 | Alfreds Futterkiste | Berlin | Germany |
| 2 | Ana Trujillo Emparedados | México D.F. | Mexico |
| 3 | Antonio Moreno Taquería | México D.F. | Mexico |
| 4 | Around the Horn | London | UK |
The following SQL statement selects all customers from the country "Mexico".
SELECT * FROM Customers WHERE Country = 'Mexico';
The result set would be:
| CustomerID | CustomerName | City | Country |
|---|---|---|---|
| 2 | Ana Trujillo Emparedados | México D.F. | Mexico |
| 3 | Antonio Moreno Taquería | México D.F. | Mexico |
Note: SQL uses single quotes for text values (most database systems will also accept double quotes).
The following SQL statement selects all customers with a CustomerID greater than 2.
SELECT * FROM Customers WHERE CustomerID > 2;
Numeric values should not be enclosed in quotes.
You can use various operators in the WHERE clause to build your conditions.
| Operator | Description |
|---|---|
= |
Equal |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal |
<= |
Less than or equal |
<> or != |
Not equal |
BETWEEN |
Between a certain range |
LIKE |
Search for a pattern |
IN |
To specify multiple possible values for a column |
We will cover these operators in more detail in the upcoming chapters.