← Homepage

CTEs and Subqueries

October 11, 2026

Author: Daniel Jordan Viray

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?

As CTEs — read top to bottom

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_idhba1c
28.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.

As a subquery — read inside out

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_idhba1c
28.8

Identical result. But you parse it backwards: find the innermost query first, then work outward. Fine for one nesting — miserable at three.

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