SQL WHERE Clause

The SQL WHERE Clause

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.


Syntax

SELECT column1, column2, ...
FROM table_name
WHERE condition;

Demo Database

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

Example 1: Text Field Condition

The following SQL statement selects all customers from the country "Mexico".

WHERE with Text Value

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).


Example 2: Numeric Field Condition

The following SQL statement selects all customers with a CustomerID greater than 2.

WHERE with Numeric Value

SELECT * FROM Customers
WHERE CustomerID > 2;

Numeric values should not be enclosed in quotes.


Operators in The WHERE Clause

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.