CTEs with WITH: readable step-by-step queries
In the previous lesson we ended with a query that repeated the same subquery twice. It worked, but it was hard to read. A CTE (Common Table Expression) solves that problem: you give a name to a SELECT at the beginning of the query with the word WITH, and then you use it as if it were a table, as many times as you like. It is the modern and readable way to build complex queries step by step, each with a name that explains its purpose.
WITH order_totals AS (
SELECT order_id, SUM(quantity * unit_price) AS order_total
FROM order_items
GROUP BY order_id
)
SELECT o.order_id, o.order_date, ot.order_total
FROM orders o
JOIN order_totals ot ON ot.order_id = o.order_id
WHERE ot.order_total > (SELECT AVG(order_total) FROM order_totals)
ORDER BY ot.order_total DESC;Read the query above from top to bottom like a recipe: first we compute the total of each order and call it order_totals; then we join that temporary table with orders and filter the orders above the average. The CTE exists only during this statement; it is not saved in the database. Compared with the previous lesson's version, the logic is the same but the total calculation is written only once.
Several chained CTEs
You can define several CTEs separated by commas, and each can use the previous ones. This turns a long query into a sequence of small steps, easy to test one by one: run each inner SELECT on its own to check that it returns what you expect. This habit of building and verifying in layers saves a lot of debugging time.
WITH valid_orders AS (
SELECT order_id, customer_id FROM orders WHERE status <> 'cancelled'
),
customer_totals AS (
SELECT vo.customer_id, SUM(oi.quantity * oi.unit_price) AS total_spent
FROM valid_orders vo
JOIN order_items oi ON oi.order_id = vo.order_id
GROUP BY vo.customer_id
)
SELECT c.name, ct.total_spent
FROM customer_totals ct
JOIN customers c ON c.customer_id = ct.customer_id
WHERE ct.total_spent > (SELECT AVG(total_spent) FROM customer_totals)
ORDER BY ct.total_spent DESC;Recursive CTEs (advanced level)
With WITH RECURSIVE a CTE can refer to itself, which lets you generate sequences or walk hierarchical structures such as an org chart or nested categories. It has two parts joined with UNION ALL: the anchor query, which gives the first row, and the recursive part, which starts from the rows already produced until a stop condition halts it. If you forget that condition, the loop never ends. To begin, it is enough to understand the number-generating example: it is useful, for instance, to build a calendar and detect days with no sales.
-- Numbers 1 to 5
WITH RECURSIVE numbers(n) AS (
SELECT 1 -- anchor
UNION ALL
SELECT n + 1 FROM numbers -- recursive step
WHERE n < 5 -- stop condition
)
SELECT n FROM numbers;
-- In PostgreSQL there is also a built-in shortcut
SELECT generate_series(1, 5) AS n;A good use of CTEs is documenting your reasoning. Choose names that explain the content of each step (order_totals, valid_orders, customer_totals) and your query will read almost like a text. When a colleague reviews it six months from now, or you yourself, you will immediately understand what each fragment does. If a CTE is used only once and is trivial, a subquery is also fine; the rule is to pick the form that is easiest to read, not the shortest.
✎ Mes notes
Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères