14. CTEs & Capstone
WITH, recursive queries, and everything you know at once.
The lesson
CTEs & Capstone
You can rank, accumulate, and see rows in relation to each other now. One problem remains: the more you know, the longer your queries get. A "top 3 customers" query written with subqueries alone can nest three levels deep before you blink — readable at the moment you write it, unreadable the moment you come back.
This chapter gives you the tool that fixes exactly that — the CTE, or Common Table Expression — and then hands you the whole path at once.
Why name a query?
Without CTEs, a "months with good revenue" query nests its logic inside parentheses:
SELECT month, revenue
FROM (SELECT strftime('%Y-%m', invoice_date) AS month, SUM(total) AS revenue
FROM invoices
GROUP BY strftime('%Y-%m', invoice_date))
WHERE revenue > 3;
Readable enough. But watch what happens when the inner step grows into three steps — the query starts reading from the inside out, and the parentheses pile up like spaghetti. The CTE turns that inside-out reading into a top-down story:
WITH monthly_revenue AS (
SELECT strftime('%Y-%m', invoice_date) AS month, SUM(total) AS revenue
FROM invoices
GROUP BY strftime('%Y-%m', invoice_date)
)
SELECT month, revenue FROM monthly_revenue WHERE revenue > 3;
A CTE gives a subquery a name — WITH monthly_revenue AS (...). From that point on, the rest of the query can use monthly_revenue like a table. The database computes it once, up front. The query reads like the recipe it is: first the monthly revenue, then the question about it.
Chaining CTEs
The real power shows up when a query needs several named steps, because each CTE can read the ones before it:
WITH track_sales AS (
SELECT track_id, SUM(quantity) AS units,
SUM(quantity * unit_price) AS revenue
FROM invoice_lines
GROUP BY track_id
),
album_sales AS (
SELECT a.title,
COALESCE(SUM(ts.units), 0) AS units,
COALESCE(SUM(ts.revenue), 0) AS revenue
FROM albums a
LEFT JOIN tracks t ON t.album_id = a.id
LEFT JOIN track_sales ts ON ts.track_id = t.id
GROUP BY a.id
)
SELECT title, units, revenue FROM album_sales;
Two CTEs, comma-separated, each one a step. album_sales reads track_sales as if it were a table — no nested parentheses, no reading backwards. And because CTEs are just named result sets, you can JOIN them like any table:
WITH totals AS (
SELECT customer_id, SUM(total) AS spent
FROM invoices GROUP BY customer_id
)
SELECT c.first_name, c.last_name, c.country, t.spent
FROM customers c
JOIN totals t ON t.customer_id = c.id
ORDER BY t.spent DESC;
Subqueries give you the same results — CTEs give you the same results with names. In a report with three steps, that difference is everything.
WITH RECURSIVE: queries that walk
Now the interesting part. A CTE can reference itself, building rows on top of its own previous rows. That's a recursive CTE, and it's how you walk trees in SQL — like the store's org chart, where every employee has a reports_to.
WITH RECURSIVE org AS (
SELECT id, first_name, last_name, title, 0 AS depth
FROM employees WHERE reports_to IS NULL
UNION ALL
SELECT e.id, e.first_name, e.last_name, e.title, org.depth + 1
FROM employees e
JOIN org ON e.reports_to = org.id
)
SELECT * FROM org ORDER BY depth, id;
Two members, joined by UNION ALL:
- The anchor member — the first
SELECT. It supplies the starting rows: Jane Foster, the one employee withreports_to IS NULL, at depth 0. - The recursive member — the second
SELECT. It joinsemployeestoorg— the CTE itself — and produces the next layer, one level deeper.
Watch the recursion grow, round by round:
| Round | What gets added |
|---|---|
| 1 | Jane Foster (depth 0) |
| 2 | Tom, Sofia, Ken — her direct reports (depth 1) |
| 3 | Ana, Marcus, Priya — their reports (depth 2) |
| 4 | Nobody. JOIN org finds nothing new — the walk is done |
The termination is built in: each round the recursive member runs against the rows from the previous round; as soon as a round produces nothing, the recursion stops. (SQLite stops after 1000 rounds no matter what, so you can't accidentally loop forever — you just get an error if you do.)
Generating series: data where there is none
The same mechanism can build rows out of thin air — a calendar, for example. The owner wants every month since the store opened, including the ones with zero sales:
WITH RECURSIVE months AS (
SELECT '2022-01-01' AS first_day
UNION ALL
SELECT strftime('%Y-%m-%d', first_day, '+1 month')
FROM months WHERE first_day < '2024-03-01'
),
monthly_sales AS (
SELECT strftime('%Y-%m', invoice_date) AS month, SUM(total) AS revenue
FROM invoices GROUP BY strftime('%Y-%m', invoice_date)
)
SELECT strftime('%Y-%m', m.first_day) AS month,
COALESCE(s.revenue, 0) AS revenue
FROM months m
LEFT JOIN monthly_sales s ON s.month = strftime('%Y-%m', m.first_day);
The anchor plants January 2022; the recursive member adds one month at a time until it passes March 2024 — 27 months generated, never stored, computed on demand. Then the LEFT JOIN keeps all 27 months even when no sale exists, and COALESCE turns the missing ones into honest zeros.
Putting it all together
Recursion, CTEs, joins, windows, rounding — the capstones ahead want them all in one query. Here's the shape you'll be building: a CTE that computes a layer of data, a second CTE that adds context to it, and a final SELECT that decorates the result with window functions:
WITH monthly AS (
SELECT strftime('%Y-%m', invoice_date) AS month, SUM(total) AS revenue
FROM invoices
WHERE strftime('%Y', invoice_date) = '2023'
GROUP BY strftime('%Y-%m', invoice_date)
),
year_total AS (
SELECT SUM(revenue) AS total FROM monthly
)
SELECT month, revenue,
SUM(revenue) OVER (ORDER BY month) AS running_total,
ROUND(100.0 * revenue / (SELECT total FROM year_total), 2) AS share
FROM monthly ORDER BY month;
Read it top to bottom: monthly revenue for 2023 → the year's grand total → each month with its share of the year. Every tool you've met since chapter 1, standing in a straight line.
What you just learned
- A CTE (
WITH name AS (...)) names a subquery so the rest of the query can use it like a table. - CTEs chain: each one can read the ones before it, turning nested parentheses into a top-down story.
- CTEs join like tables — compute in one, enrich in the other.
WITH RECURSIVElets a CTE reference itself: an anchor member starts the walk, a recursive member extends it, and it ends when a round finds nothing new.- Recursion can generate data — series of numbers or months — which you then
LEFT JOINagainst real data to expose the gaps. - The capstone pattern: CTEs for the layers, joins for the context, windows for the rankings and totals.
Dialect note. The
RECURSIVEkeyword is required by SQLite, PostgreSQL and MySQL 8, but not by SQL Server and Oracle — they recurse with a plainWITH. All of them support the same anchor +UNION ALL+ recursive member structure, though Oracle also offers its olderCONNECT BYsyntax. SQLite's default recursion budget is 1000 rounds. Everything else in this chapter — naming, chaining, joining CTEs — is identical across all major databases.
That's the end of the path. The last two exercises are capstones: nothing new to learn, everything to use.