SQL NULL Handling Cheatsheet
IS NULL, COALESCE, NULLIF, and null-safe equality.
Test for NULL
where shipped_date is null -- right
where shipped_date is not null
-- where shipped_date = null -- wrong for testing missingness NULL marks a missing or unknown value. Ordinary comparison
operators such as =, <>, and
> involving a null evaluate to UNKNOWN, which a
WHERE clause does not keep. Null-aware predicates such as
IS NULL and IS [NOT] DISTINCT FROM are designed
for these cases.
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
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_id Guard divide-by-zero
select sum(cost) / nullif(sum(price), 0) as cost_ratio
from products
Aggregates skip nulls (except count(*)). NOT IN is
especially risky when its list or subquery can contain NULL:
rows that do not otherwise match can evaluate to UNKNOWN and
disappear. NOT EXISTS is usually clearer for missing-match
checks. Nulls also appear on the unmatched side of an outer join, so test
those with IS NULL, not = NULL.
Related
Find missing values with IS NULL.
IS NULL, COALESCE, NULLIF, and null-safe logic.
Practice WITH clauses and step-by-step reports.
Use IS NULL instead of equality.
WHERE is evaluated before SELECT aliases exist.
Keep NULLs from silently changing filter results.