Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 03 / Topic 4 of 9

The NULL-safe toolkit

Three tools turn NULL from a hazard into a non-event.

COALESCE(a, b, ...) returns the first non-NULL argument — the standard "show a fallback" tool:

SELECT first_name,
       COALESCE(city, 'Unknown') AS city
FROM customers
ORDER BY customer_id;
 first_name |  city   
------------+---------
 Asha       | Pune
 Ravi       | Delhi
 Meera      | Chennai
 John       | London
 Sara       | Unknown
 Vikram     | Pune
(6 rows)

NULLIF(a, b) returns NULL when a = b — the classic guard against division by zero (x / NULLIF(y, 0) gives NULL instead of an error). You will see it earning its keep in Stage 2's growth-rate queries.

IS DISTINCT FROM is <> that treats NULL as an ordinary, comparable value — two NULLs are not distinct, a NULL and a value are:

SELECT NULL <> 5                 AS plain_compare,
       NULL IS DISTINCT FROM 5   AS null_safe,
       NULL IS NOT DISTINCT FROM NULL AS two_unknowns_same;
 plain_compare | null_safe | two_unknowns_same 
---------------+-----------+-------------------
               | t         | t
(1 row)

When comparing two possibly-NULL columns (does the new value differ from the old?), IS DISTINCT FROM says exactly what you mean, with no unknowns leaking through.

🧪 Quick quiz — answer from memory, then check.

  1. COALESCE(NULL, NULL, 'x', 'y') returns…?
  2. What is NULLIF(total, 0) for?
Show the answers
  1. 'x' — the first non-NULL argument.
  2. Turning a 0 into NULL so a division becomes NULL instead of an error.

Done here? The practice set for Part 3 — 7 exercises with solutions — is on the part page.

Search the guide