← Homepage

COALESCE and NULLIF

October 11, 2026

Author: Daniel Jordan Viray

SQL notes · clinical toy data · defaults for NULLs, and taming placeholder zeros

The idea. COALESCE returns the first non-NULL value in its list — for defaults and display. NULLIF(a, b) returns NULL when a = b — for turning placeholder values (like a 0 that means "unknown") back into real NULLs so they don't corrupt your math.

Toy data

labs — patient 2's result never came back (NULL)

patient_idtest_datehba1c
12024-01-058.2
22024-02-11NULL
32024-03-017.1

doses — patient 2's weight recorded as 0 (missing-data placeholder)

patient_iddose_mgweight_kg
1500.080.0
2850.00.0
31000.095.0

COALESCE: fill the gap for display

SELECT patient_id,
       COALESCE(CAST(hba1c AS TEXT), 'pending') AS result
FROM labs ORDER BY patient_id;
patient_idresult
18.2
2pending
37.1

Reads left to right, stops at the first non-NULL. The lab value if present, the word "pending" otherwise.

COALESCE changes your averages — know which question you're answering

SELECT ROUND(AVG(hba1c), 2) AS avg_observed,
       ROUND(AVG(COALESCE(hba1c, 0)), 2) AS avg_zero_filled
FROM labs;
avg_observedavg_zero_filled
7.655.1

AVG(hba1c) ignores NULLs (denominator 2 → 7.65: the mean of observed results). AVG(COALESCE(hba1c, 0)) fills the gap first (denominator 3 → 5.10: the mean assuming missing = 0). Neither is "right" — but they answer different questions, and filling blindly can manufacture a worse number than the honest one.

NULLIF: turn a placeholder zero back into unknown

SELECT patient_id,
       ROUND(dose_mg / NULLIF(weight_kg, 0), 2) AS mg_per_kg
FROM doses ORDER BY patient_id;
patient_idmg_per_kg
16.25
2NULL
310.53

Patient 2's weight of 0 isn't a real weight — it's how "unknown" got typed in. Without NULLIF this query divides by zero (error, or worse, an Infinity that flows downstream). NULLIF(weight_kg, 0) converts the placeholder back into what it means: unknown → the result is NULL, honestly.

Watch out.
Prove it. Every query on this page was run against SQLite and the tables show actual output — not hand-typed guesses.