In two sentences
NULL means "we don't know", not zero and not empty, so any comparison with it is neither true nor false but
unknown, and WHERE keeps only rows that are true. That's why NULLs vanish from filters, never match in joins,
and quietly change counts and averages.
See it
| customer_id | |
|---|---|
| c1 | ana@shop.com |
| c2 | (empty string) |
| c3 | (three spaces) |
| c4 | NULL |
| query | rows returned | why |
|---|---|---|
WHERE email = NULL | none | = NULL is always unknown |
WHERE email IS NULL | c4 | the right test |
WHERE email <> 'ana@shop.com' | c2, c3 | c4 is unknown, so it's dropped too |
count(*) | 4 | counts rows |
count(email) | 3 | skips NULLs, but counts the blanks as real emails |
c2, c3 and c4 all mean "no email", but SQL sees three different things.
In SQL
Turn every flavour of "missing" into one NULL first, then count:
SELECT
customer_id,
nullif(lower(trim(email)), '') AS email -- '' and ' ' become NULL
FROM customers;Then decide what missing means for each output, explicitly:
SELECT
count(*) AS customers,
count(email) AS with_email,
coalesce(sum(amount), 0) AS revenue -- sum of only NULLs is NULL, not 0
FROM ...To compare two columns where NULL should equal NULL (for example "did this value change?"):
WHERE old.email IS DISTINCT FROM new.emailold.email <> new.email would miss a change from NULL to a value, and from a value to NULL.
Common mistakes
NOT INwith a NULL in the list.WHERE id NOT IN (SELECT customer_id FROM blocked)returns nothing if anycustomer_idinblockedis NULL. UseNOT EXISTS.avgignores NULLs. The average of 10, NULL, 20 is 15, not 10. Decide if missing means 0 or "excluded".- Joins never match on NULL. Two rows with a NULL key don't join to each other. Usually that's what you want; sometimes it hides unmatched data.
- Treating blanks as values.
''and' 'passIS NOT NULLand get counted. Normalise first. GROUP BYputs all NULLs in one group. Unlike=, grouping treats NULLs as equal, so a single NULL bucket appears in reports. Label it.
What an interviewer asks next
- "Is a missing amount zero, or unknown?" The answer changes the report. Say which you chose and why.
- "How would you catch this in production?" A data-quality check on the NULL rate per column, with a threshold.
Go further
Modern SQL's page on three-valued logic is short and precise. The Trino pages list IS DISTINCT FROM,
coalesce and nullif.
Practise it
Clean Customer Contact Data is this lesson as a problem. Daily Revenue Report has the sum of only NULLs
trap.