SQL/Filtering & sorting 7 min
NULLs and COALESCE
The missing-value rules that quietly break queries.
nullcoalescenullif
NULL means unknown, not zero and not empty string. Any comparison with it is neither true nor false, so `= NULL` never matches — use IS NULL and IS NOT NULL.
sql · editable
loading editor…
COALESCE returns the first non-NULL argument, which is how you supply a default. NULLIF does the reverse: it turns a sentinel value into NULL, handy for avoiding division by zero.
sql · editable
loading editor…
Try it: Keep only customers whose spend is 0.
Aggregates skip NULLs: COUNT(col) ignores them while COUNT(*) counts the row. AVG divides by the non-NULL count, so a NULL is not the same as a zero.
practice this