Common Table Expressions (WITH)
Syntax
WITH step_one AS (
SELECT …
),
step_two AS (
SELECT … FROM step_one …
)
SELECT … FROM step_two;
- Each CTE is a named, temporary result that exists only for this one query
- Later CTEs can use earlier ones
- The final SELECT (or INSERT/UPDATE/DELETE) uses them like tables
Why use CTEs?
- Readability: each step has a meaningful name, read top to bottom like a story
- Reuse: reference the same CTE several times
- Debugging: run the query step by step (
SELECT * FROM step_one) - Avoid fan-out: aggregate in separate CTEs, then join them
CTE vs subquery
They're logically the same. A CTE is a subquery moved to the top and given a name. Since PostgreSQL 12, simple CTEs are inlined (optimized like subqueries), so there's usually no performance cost.
WITH x AS MATERIALIZED (…)forces it to be computed onceAS NOT MATERIALIZEDforces inlining
Data-modifying CTEs (PostgreSQL)
CTEs can contain INSERT, UPDATE or DELETE with RETURNING:
WITH moved AS (DELETE FROM … RETURNING *)
INSERT INTO archive SELECT * FROM moved;
Several changes happen in one atomic statement.
Style tips
- Name CTEs by what they contain:
monthly_totals,active_users,ranked - One idea per CTE
- 2–5 CTEs is typical; if you need 15, consider a view or a function
Example
-- Monthly budget report, step by step
WITH monthly AS ( -- 1. total per user per month
SELECT user_id,
date_trunc('month', spent_on)::date AS month,
sum(amount) AS spent
FROM expenses
GROUP BY user_id, date_trunc('month', spent_on)
),
with_budget AS ( -- 2. add the budget
SELECT u.name, m.month, m.spent, u.monthly_budget,
round(100.0 * m.spent / u.monthly_budget, 1) AS pct_used
FROM monthly m
JOIN users u ON u.id = m.user_id
)
SELECT name, to_char(month, 'Mon') AS month, spent, monthly_budget, pct_used,
CASE WHEN pct_used > 40 THEN '⚠️ watch out' ELSE '✅ ok' END AS status
FROM with_budget
WHERE month = '2026-11-01'
ORDER BY pct_used DESC;
-- Ravi 46.8% ⚠️, Sita 29.9% ✅, ...
-- Reusing a CTE twice: compare each user with the overall average
WITH totals AS (
SELECT user_id, sum(amount) AS total FROM expenses GROUP BY user_id
)
SELECT u.name, t.total,
round(t.total - (SELECT avg(total) FROM totals), 2) AS vs_average
FROM totals t JOIN users u ON u.id = t.user_id
ORDER BY t.total DESC;
-- Data-modifying CTE: pay all of Asha's bills and log them as expenses, atomically
WITH paid AS (
UPDATE bills SET paid = true
WHERE user_id = 1 AND NOT paid
RETURNING user_id, title, amount, due_date
)
INSERT INTO expenses (user_id, category_id, title, amount, spent_on, tags)
SELECT user_id, 3, title || ' payment', amount, due_date, '{bill}'
FROM paid
RETURNING title, amount;
-- Rent payment 15000.00, Internet payment 1500.00