Topic 1 of 5 · 4 min read
Filtering rows with SELECT and WHERE
Goal: Write a query that returns exactly the rows a written request asks for, including the rows where the filtered column is NULL.
A query is a request in four parts: which columns, from which table, filtered by which condition, in which order. Write the request in a sentence first, then translate it, and always ask what happens to rows where the filtered column is NULL.
Check yourself · 1 of 3
A table has 50 rows with a NULL in the column phone. What does SELECT * FROM contacts WHERE phone = NULL return?
Why it matters
Every report, every API endpoint and every AI-written query starts here. A filter that is slightly off does not fail. It returns a plausible table with the wrong rows, and nobody notices until a number is wrong.
How to do it
- Name the columns you need.
SELECT id, email, created_atis better thanSELECT *. It is faster, and it does not break when someone adds a column. - Filter with
WHERE. Combine conditions withANDandOR, and add brackets when you mix them.ANDbinds tighter thanOR, soa OR b AND cmeansa OR (b AND c). - Handle NULL on purpose. NULL means "unknown", and nothing equals unknown, not even another NULL.
WHERE coupon = NULLreturns no rows. WriteWHERE coupon IS NULL. - Sort and limit together.
ORDER BY created_at DESC LIMIT 10gives the ten newest.LIMITwithoutORDER BYreturns ten rows in no promised order. - Check the result against the request. Count a few rows by hand.
Before and after
The request: "all customers who have not been given a discount code."
-- Before
SELECT * FROM customers WHERE discount_code != 'WELCOME10';
This looks right but drops every customer whose discount_code is NULL, because NULL != 'WELCOME10' is unknown, and WHERE keeps only rows that are true. The request meant the opposite of what the query does for most customers.
-- After
SELECT id, email
FROM customers
WHERE discount_code IS NULL;
What goes wrong
= NULLand!= valueon a nullable column. Both silently skip the NULL rows. UseIS NULL,IS NOT NULLorIS DISTINCT FROM.- Mixed
ANDandORwithout brackets. The query runs and returns more or fewer rows than intended. LIMITwithoutORDER BY. The test passes today and returns different rows after the next vacuum or index change.SELECT *in application code. A new wide column, such as a text blob, suddenly travels over the network on every call.
Examples
The missing NULL rows
A table orders has 100 rows. 70 have status = 'paid', 20 have 'refunded' and 10 have a NULL status.
SELECT count(*) FROM orders WHERE status != 'paid';
This returns 20, not 30. The 10 NULL rows are neither equal nor unequal to 'paid'. To count everything that is not paid, write WHERE status IS DISTINCT FROM 'paid' in PostgreSQL, or WHERE status != 'paid' OR status IS NULL.
Brackets around OR
Request: active users who are either admins or editors.
-- Wrong: returns every admin, active or not
SELECT id FROM users WHERE active = true AND role = 'admin' OR role = 'editor';
-- Right
SELECT id FROM users WHERE active = true AND (role = 'admin' OR role = 'editor');
Key points
- Write the request in one sentence first, then translate it into columns, table, filter and order.
- NULL equals nothing, so use IS NULL and IS NOT NULL; a comparison with NULL is never true.
- A != filter on a nullable column also drops the NULL rows unless you handle them.
- AND binds tighter than OR, so bracket mixed conditions.
- LIMIT without ORDER BY returns rows in no promised order.
Common mistakes
- Writing
WHERE column = NULLand getting an empty result. - Filtering with
!=on a nullable column and losing the NULL rows without noticing. - Mixing AND and OR without brackets.
- Using LIMIT without ORDER BY and treating the result as stable.
Check yourself · 2 of 3
A users table has 40 rows with plan = 'free', 30 with plan = 'pro' and 10 with plan NULL. How many rows does WHERE plan != 'free' return?
Check yourself · 3 of 3
You need the five most recent signups. Which query does that reliably?
Practice items, not counted towards your mastery.
Start here
- PostgreSQL tutorial (opens in a new tab)DocsFree
Official walk-through of tables, joins, aggregates and transactions on a small schema.
- SQLBolt: interactive SQL lessons (opens in a new tab)CourseFree
Short browser exercises on filters, joins and aggregates with instant feedback.
- Use The Index, Luke: SQL indexing and tuning (opens in a new tab)BookFree
A free book on how indexes work and how to design them for real queries.