October 11, 2026
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.
labs — patient 2's result never came back (NULL)
| patient_id | test_date | hba1c |
|---|---|---|
| 1 | 2024-01-05 | 8.2 |
| 2 | 2024-02-11 | NULL |
| 3 | 2024-03-01 | 7.1 |
doses — patient 2's weight recorded as 0 (missing-data placeholder)
| patient_id | dose_mg | weight_kg |
|---|---|---|
| 1 | 500.0 | 80.0 |
| 2 | 850.0 | 0.0 |
| 3 | 1000.0 | 95.0 |
SELECT patient_id,
COALESCE(CAST(hba1c AS TEXT), 'pending') AS result
FROM labs ORDER BY patient_id;
| patient_id | result |
|---|---|
| 1 | 8.2 |
| 2 | pending |
| 3 | 7.1 |
Reads left to right, stops at the first non-NULL. The lab value if
present, the word "pending" otherwise.
SELECT ROUND(AVG(hba1c), 2) AS avg_observed,
ROUND(AVG(COALESCE(hba1c, 0)), 2) AS avg_zero_filled
FROM labs;
| avg_observed | avg_zero_filled |
|---|---|
| 7.65 | 5.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.
SELECT patient_id,
ROUND(dose_mg / NULLIF(weight_kg, 0), 2) AS mg_per_kg
FROM doses ORDER BY patient_id;
| patient_id | mg_per_kg |
|---|---|
| 1 | 6.25 |
| 2 | NULL |
| 3 | 10.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.
COALESCE away NULLs before you understand why they're NULL — a missing lab and a lab of 0 are different facts.COALESCE(a, b) is standard SQL (IFNULL/NVL are dialect spellings of the two-argument case).NULLIF also guards rate calculations: events / NULLIF(days, 0) never divides by zero.