October 11, 2026
SQL notes · clinical toy data · same question, two shapes — readability is the difference
The idea. A CTE (WITH …) names an
intermediate result up front; a subquery nests it inline. Same
question, same answer, usually the same query plan — the difference is how a human
reads it six months later.
The question (reusing the HbA1c readings from the window-functions page): which patients' most recent HbA1c exceeds 8.0?
WITH latest AS ( SELECT patient_id, MAX(reading_date) AS d FROM a1c_readings GROUP BY patient_id ), latest_vals AS ( SELECT r.patient_id, r.hba1c FROM a1c_readings r JOIN latest l ON r.patient_id = l.patient_id AND r.reading_date = l.d ) SELECT patient_id, hba1c FROM latest_vals WHERE hba1c > 8.0 ORDER BY patient_id;
| patient_id | hba1c |
|---|---|
| 2 | 8.8 |
latest: each patient's most recent reading date.
latest_vals: the actual values on those dates. Then filter.
Each step has a name; the query reads like a recipe.
SELECT r.patient_id, r.hba1c
FROM a1c_readings r
JOIN (SELECT patient_id, MAX(reading_date) AS d
FROM a1c_readings GROUP BY patient_id) l
ON r.patient_id = l.patient_id AND r.reading_date = l.d
WHERE r.hba1c > 8.0 ORDER BY r.patient_id;
| patient_id | hba1c |
|---|---|
| 2 | 8.8 |
Identical result. But you parse it backwards: find the innermost query first, then work outward. Fine for one nesting — miserable at three.
latest, not cte1) — future-you will thank present-you.