Filtering, Sorting and the NULL Trap
Work through a support request with WHERE, pattern matching, ORDER BY and LIMIT, and learn why NULL quietly changes what every comparison means.
Contentsand lesson path
On this page
- The task
- Setup: add customers
- Step 1: filter rows and combine conditions
- Step 2: match text
- Step 3: fall into the NULL trap and climb out
- Step 4: sort, then take a stable top three
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of SQL Fundamentals
- Tables, Rows and a First Session in psql Concept · 20 min
- Filtering, Sorting and the NULL Trap Worked example · 25 min
- Joins and Subqueries Without Multiplying Rows Lab · 30 min
- Turning Rows into Business Metrics Lab · 25 min
- Tables, Views and Changing Data Safely Lab · 25 min
- Check: Answer Questions About an Unseen Schema Knowledge check · 10 questions
What you will learn
- Write SELECT queries that filter, sort and limit rows, handling NULL with three-valued logic correctly.
01. The task
The marketing team of the little store from the first lesson sends one message with four asks:
- Spanish customers, for a local campaign.
- Accessories that cost 30 or less, cheapest first.
- Every product whose name contains the word cable.
- The three cheapest products in the catalogue — and the same three every time the report runs.
They also mention, almost as an afterthought, that some customers have no country recorded yet, and they would like a list of those too. That last line is where most SQL bugs hide, so this worked example treats it as the main event. You will build every query against real data, run it, and read the output before moving on.
02. Setup: add customers
Keep the store database from the previous lesson and add the customers table. Note that country has no NOT NULL — the column may hold NULL, which is exactly the situation the marketing team described:
CREATE TABLE customers (
id integer PRIMARY KEY,
name text NOT NULL,
email text NOT NULL UNIQUE,
country text,
joined_at date NOT NULL
);
INSERT INTO customers (id, name, email, country, joined_at) VALUES
(1, 'Amara Ndiaye', '[email protected]', 'SN', '2026-01-12'),
(2, 'Ben Carter', '[email protected]', NULL, '2026-02-03'),
(3, 'Clara Ruiz', '[email protected]', 'ES', '2026-03-21'),
(4, 'Dmitri Volkov', '[email protected]', NULL, '2026-03-29'),
(5, 'Elin Johansson', '[email protected]', 'SE', '2026-04-15'),
(6, 'Farid Haddad', '[email protected]', 'ES', '2026-05-02');CREATE TABLE
INSERT 0 603. Step 1: filter rows and combine conditions
Ask 1: the store's Spanish customers. WHERE keeps the rows for which the condition is true, using the comparison operators =, <>, <, <=, >, >=:
SELECT name, country FROM customers WHERE country = 'ES'; name | country
--------------+---------
Clara Ruiz | ES
Farid Haddad | ES
(2 rows)Combine conditions with AND, OR and NOT. When you mix AND with OR, parenthesise: AND binds more tightly, so a OR b AND c means a OR (b AND c). Start with AND alone, which keeps only the rows that pass both tests:
SELECT name, price FROM products
WHERE category = 'accessories' AND price <= 30
ORDER BY price; name | price
---------------+-------
USB-C cable | 9.90
Mouse pad | 12.50
HDMI cable 2m | 12.50
Laptop stand | 29.00
(4 rows)Now mix in OR. Where the parentheses go decides whether an expensive monitor stays in the report:
SELECT name, category, price FROM products
WHERE category = 'displays'
OR (category = 'peripherals' AND price < 100)
ORDER BY price; name | category | price
---------------------+-------------+--------
Webcam 1080p | peripherals | 45.00
Mechanical keyboard | peripherals | 89.00
27-inch monitor | displays | 249.00
(3 rows)That query keeps every display and only the cheap peripherals, so the 249.00 monitor is in. Move the parentheses and the price limit now applies to both categories, so the monitor drops out:
SELECT name, category, price FROM products
WHERE (category = 'displays' OR category = 'peripherals')
AND price < 100
ORDER BY price; name | category | price
---------------------+-------------+-------
Webcam 1080p | peripherals | 45.00
Mechanical keyboard | peripherals | 89.00
(2 rows)Two shorthands cover common ranges and sets: BETWEEN a AND b is inclusive on both ends, and IN (...) matches any value in a list. Both can be negated with NOT:
SELECT name, category, price FROM products
WHERE price BETWEEN 10 AND 50
AND category IN ('accessories', 'peripherals')
ORDER BY price; name | category | price
---------------+-------------+-------
Mouse pad | accessories | 12.50
HDMI cable 2m | accessories | 12.50
Laptop stand | accessories | 29.00
Webcam 1080p | peripherals | 45.00
(4 rows)04. Step 2: match text
For ask 3, equality cannot help because you want a substring. LIKE matches text against a pattern where % stands for any run of characters and _ for exactly one. ILIKE is the case-insensitive version — one letter that saves you from wrapping both sides in lower():
SELECT name, price FROM products WHERE name ILIKE '%cable%' ORDER BY price; name | price
---------------+-------
USB-C cable | 9.90
HDMI cable 2m | 12.50
(2 rows)The pattern needs a % on both sides: 'cable%' would only match names that start with cable, which none do. Beyond patterns, PostgreSQL offers string functions you will recognise from any language: upper, lower, length, trim, and concatenation with ||. Use them in WHERE when a pattern is not enough — for example WHERE length(name) > 20.
05. Step 3: fall into the NULL trap and climb out
Now the afterthought: list the customers with no country. The obvious attempt is = NULL, and it is the most common first mistake in SQL. Run it:
SELECT name FROM customers WHERE country = NULL; name
------
(0 rows)No error, no rows — the query simply cannot be right. The reason is three-valued logic. Comparing anything with NULL yields not true or false but UNKNOWN, and WHERE keeps only rows it can prove true. UNKNOWN is dropped, so Ben and Dmitri vanish even though their country is exactly the value you were looking for. NULL means "value absent", and absent values refuse every comparison.
Test for absence explicitly with IS NULL, and for presence with IS NOT NULL:
SELECT name FROM customers WHERE country IS NULL; name
---------------
Ben Carter
Dmitri Volkov
(2 rows)The trap has a second jaw. A colleague asks for "everyone who is not Spanish", expecting four customers:
SELECT name, country FROM customers WHERE NOT (country = 'ES') ORDER BY name; name | country
----------------+---------
Amara Ndiaye | SN
Elin Johansson | SE
(2 rows)Two rows, and the two NULL-country customers are missing again: NOT (UNKNOWN) is still UNKNOWN, so negation cannot rescue them. If you want not Spanish, including unknowns, say it with IS DISTINCT FROM, the comparison that treats NULL as a comparable value:
SELECT name, country FROM customers WHERE country IS DISTINCT FROM 'ES' ORDER BY name; name | country
----------------+---------
Amara Ndiaye | SN
Ben Carter |
Dmitri Volkov |
Elin Johansson | SE
(4 rows)For reports, replace NULL with readable text using COALESCE, which returns its first non-NULL argument. Three small functions cover most day-to-day NULL work, and a one-line query shows each in action:
SELECT name, COALESCE(country, 'unknown') AS country FROM customers ORDER BY name; name | country
----------------+---------
Amara Ndiaye | SN
Ben Carter | unknown
Clara Ruiz | ES
Dmitri Volkov | unknown
Elin Johansson | SE
Farid Haddad | ES
(6 rows)SELECT COALESCE(NULL, 'fallback') AS use_first,
NULLIF('same', 'same') IS NULL AS null_if_equal,
CAST('42' AS integer) + 1 AS text_to_number; use_first | null_if_equal | text_to_number
-----------+---------------+----------------
fallback | t | 43
(1 row)NULLIF(a, b) returns NULL when its two arguments are equal — handy for turning empty strings or sentinel values into real NULLs before loading. CAST(x AS type) (or the PostgreSQL shorthand x::type) converts between types; never rely on adding a number to text to work by accident.
06. Step 4: sort, then take a stable top three
Ask 4 needs ORDER BY and LIMIT, plus one subtlety. First observe how NULL sorts. By default PostgreSQL treats NULL as larger than every value, so ascending order pushes it to the end:
SELECT name, country FROM customers ORDER BY country; name | country
----------------+---------
Clara Ruiz | ES
Farid Haddad | ES
Elin Johansson | SE
Amara Ndiaye | SN
Ben Carter |
Dmitri Volkov |
(6 rows)SELECT name, country FROM customers ORDER BY country NULLS FIRST; name | country
----------------+---------
Ben Carter |
Dmitri Volkov |
Clara Ruiz | ES
Farid Haddad | ES
Elin Johansson | SE
Amara Ndiaye | SN
(6 rows)Sorting by country gives ties, and ties hide the real trap of ask 4. Look at the accessories list above: Mouse pad and HDMI cable 2m both cost 12.50. When the sort key ties, PostgreSQL may return the tied rows in any order. Here both 12.50 rows fit inside LIMIT 3, so the three products are always the same, but ORDER BY price LIMIT 3 can list the two tied ones in either order; with LIMIT 2 the cut falls inside the tie and the query could return either one — the report changes between runs. Add a unique tie-breaker, such as the primary key, and the result becomes deterministic:
SELECT name, price FROM products ORDER BY price, id LIMIT 3; name | price
---------------+-------
USB-C cable | 9.90
Mouse pad | 12.50
HDMI cable 2m | 12.50
(3 rows)LIMIT applies to the sorted result, not to the rows before sorting: the answer is always the first rows of the full ordering. (Internally PostgreSQL may take shortcuts, such as keeping only the best few rows while it sorts, but they return the same rows.) To skip pages of results, add OFFSET n (LIMIT 10 OFFSET 20 means rows 21 to 30), remembering that with ties you still want the tie-breaker.
07. Common mistakes
08. Check your understanding
09. Apply it
Continue the practice project with the customers table:
- Write the query for customers outside Spain, including unknown countries, twice: once with
IS DISTINCT FROM, once withcountry <> 'ES' OR country IS NULL. Confirm both return the same four rows. - Predict, then run:
SELECT count(*) FROM customers WHERE country <> 'ES';— and explain the number using three-valued logic. - Sort products by category with
LIMIT 3first without, then with, a tie-breaker, and note which one you would ship in a report.
If you worked through the pandas lesson on tabular cleaning, compare how filtering and sorting feel there versus in SQL — same ideas, different engine.
10. Review prompt
Without looking back:
- Why does
WHERE country = NULLreturn no rows, and what are the two correct ways to test for a missing country? - Why does
NOT (country = 'ES')return fewer rows than expected, and which comparison includes the unknowns? - What do
COALESCE,NULLIFandCASTeach do? - Where does PostgreSQL place NULLs when sorting ascending, and why does a "top 3 cheapest" query need a tie-breaker?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.