Skip to main content

WHERE: Filtering Rows

WHERE filters the rows returned by a query. Only rows where the condition evaluates to TRUE are included in the result.

Prior lesson

This lesson builds on SELECT and FROM. The sample dataset is defined in the Introduction to SQL lesson.

Syntax

SELECT column1, column2
FROM table_name
WHERE condition;

Supported comparison operators:

OperatorMeaning
=Equal to
<>Not equal to
!=Not equal to (same as <>, both are accepted)
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to

Examples

Example 1: Filter by a number

SELECT
order_id,
customer_id,
total_amount
FROM orders
WHERE total_amount > 200;

Result:

order_idcustomer_idtotal_amount
11999.00
32349.00
43796.00
61349.00
72999.00
93999.00

Example 2: Filter by a string value

String values must be wrapped in single quotes.

SELECT
order_id,
order_date,
total_amount,
status
FROM orders
WHERE status = 'completed';

Result:

order_idorder_datetotal_amountstatus
12024-01-05999.00completed
22024-01-1059.98completed
32024-01-15349.00completed
42024-02-01796.00completed
72024-03-15999.00completed
82024-04-0189.97completed

Example 3: Filter by a date

SELECT
order_id,
order_date,
total_amount
FROM orders
WHERE order_date >= '2024-03-01';

Result:

order_idorder_datetotal_amount
62024-03-01349.00
72024-03-15999.00
82024-04-0189.97
92024-04-10999.00
102024-05-0124.95

Common Mistake

Cannot reference SELECT aliases in WHERE

The WHERE clause is evaluated before SELECT, so column aliases defined in SELECT are not available yet.

-- This fails
SELECT total_amount * 0.9 AS discounted_price
FROM orders
WHERE discounted_price < 100; -- ERROR: column "discounted_price" does not exist

-- This works
SELECT total_amount * 0.9 AS discounted_price
FROM orders
WHERE total_amount * 0.9 < 100;

Practice

Write a query that returns all columns from orders where the status is 'pending'.

Show answer
SELECT *
FROM orders
WHERE status = 'pending';

Expected result:

order_idcustomer_idproduct_idorder_datequantitytotal_amountstatus
9312024-04-101999.00pending
10452024-05-01524.95pending
Donate to this project