Cheatsheet
SQL NULL Handling Cheatsheet
IS NULL, COALESCE, NULLIF, and null-safe equality.
Test for NULL
IS NULL, never = NULL
where shipped_date is null -- right
where shipped_date is not null
-- where shipped_date = null -- wrong: matches no rows, everNULL means "unknown", so any comparison with it isNULL (not true), so the row drops out. That is also whyNULL = NULL is not true: the database can't confirm two unknown values are the same, so it won't say they match.
The functions
| Function | Returns |
|---|---|
coalesce(a, b, c) | First non-null argument. |
nullif(a, b) | NULL if a = b, else a. |
a is not distinct from b | Null-safe equality (two nulls count as equal). |
Defaults for display
COALESCE fills gaps
select c.first_name,
coalesce(c.phone, 'No phone on file') as phone,
coalesce(o.shipped_date, o.order_date) as effective_date
from customers as c
left join orders as o on o.customer_id = c.customer_idGuard divide-by-zero
NULLIF on the denominator
select sum(cost) / nullif(sum(price), 0) as cost_ratio
from productsWatch out
Aggregates skip nulls (except count(*)).NOT IN (… a null …) can drop every row. UseNOT EXISTS. And nulls appear from LEFT JOINnon-matches, so filter those with IS NULL, not =.
Related
End of cheatsheets