Part 06 / Topic 7 of 8
Common table expressions
WITH names a subquery and puts it first, where readers look. The derived-table query from section 5, re-told as steps:
WITH customer_totals AS (
SELECT o.customer_id,
sum(oi.quantity * oi.unit_price) AS lifetime_value
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status <> 'cancelled'
GROUP BY o.customer_id
)
SELECT c.first_name, ct.lifetime_value
FROM customer_totals AS ct
JOIN customers AS c ON c.customer_id = ct.customer_id
WHERE ct.lifetime_value > 500
ORDER BY ct.lifetime_value DESC;
first_name | lifetime_value
------------+----------------
Meera | 2108.00
Asha | 1525.00
Ravi | 949.00
(3 rows)
A CTE (common table expression) is read top-to-bottom like prose: first compute customer totals, then keep the big spenders. CTEs chain — each may use the ones before it:
WITH monthly AS (
SELECT date_trunc('month', o.order_date)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY 1
),
ranked AS (
SELECT month, revenue, rank() OVER (ORDER BY revenue DESC) AS rnk
FROM monthly
)
SELECT month, revenue FROM ranked WHERE rnk = 1;
month | revenue
------------+---------
2025-01-01 | 2069.00
(1 row)
(That rank() OVER is a window function — Part 7 is all about them; here it's just a teaser of how CTE steps stack.) GROUP BY 1 groups by the first SELECT column — common in analytics code, fine once you know it.
Choosing between them is simple: a one-off nesting fits a derived table, while anything you will read twice — or hand to another human — deserves a CTE. The plans are the same either way in modern Postgres (the MATERIALIZED fine print is a Stage 4 lesson).
🧪 Quick quiz — answer from memory, then check.
- What does WITH buy over a derived table?
- May the second CTE in a WITH use the first?
Show the answers
- The steps are named and read in order — logic first, details below; and a CTE can be referenced more than once.
- Yes — CTEs chain downward.
Exercise 7: The slowest month
What to do: Using a CTE for monthly delivered revenue, find the single worst month.
Sample output:
month | revenue
------------+---------
2025-02-01 | 135.00
(1 row)
💡 Hint: WITH monthly AS (...) SELECT ... ORDER BY revenue LIMIT 1.
Show the solution to Exercise 7
-- Exercise 7: The slowest month
WITH monthly AS (
SELECT date_trunc('month', o.order_date)::date AS month,
sum(oi.quantity * oi.unit_price) AS revenue
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status = 'delivered'
GROUP BY 1
)
SELECT month, revenue
FROM monthly
ORDER BY revenue, month
LIMIT 1;