Multiple CTEs: build a report in stages
Overview
Use several comma-separated CTEs after one WITH to express a sequence of logical transformations. Give each stage a clear purpose and a known row grain.
First example
WITH units AS ( SELECT product_id, SUM(quantity) AS n FROM order_items GROUP BY product_id), popular AS ( SELECT product_id, n FROM units WHERE n >= 2)SELECT p.name, u.n FROM popular u JOIN products p ON p.id = u.product_idORDER BY p.id;Observed SQLite result (rows in JSON):
[ [ "Notebook", 2 ], [ "Pen", 7 ]]How it works
The first query computes units per product, then filters the summary to products with at least two units. The second builds separate item totals and customer order counts before producing a customer report. The CTE stages are written in dependency order; this is a readable portable pattern, not a claim about physical execution. Aggregate at the intended grain before joining. LEFT JOIN and COALESCE retain customers without orders.
Practical example
WITH counts AS ( SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id), units AS ( SELECT o.customer_id, SUM(i.quantity) AS n FROM orders o JOIN order_items i ON i.order_id = o.id GROUP BY o.customer_id)SELECT c.name, COALESCE(a.n, 0), COALESCE(b.n, 0)FROM customers c LEFT JOIN counts a ON a.customer_id = c.idLEFT JOIN units b ON b.customer_id = c.id ORDER BY c.id;Observed SQLite result (rows in JSON):
[ [ "Alice", 2, 6 ], [ "David", 1, 4 ], [ "Sara", 0, 0 ]]Practice and mistakes
Practice: change the first threshold to 3; only Pen remains. In the second query explain why joining detail rows before counting orders can overcount Alice. Keep the two stages rather than combining unrelated grains.