Common table expressions (WITH)
Name an intermediate result and build a query step by step.
A common table expression (CTE) gives a name to a query so you can use it like a table in the statement that follows. It is written with WITH.
WITH big_orders AS (
SELECT user_id, total
FROM orders
WHERE total > 100
)
SELECT u.name, COUNT(*) AS n
FROM big_orders b
JOIN users u ON u.id = b.user_id
GROUP BY u.name;Why use them
- The query reads top to bottom, like steps in a recipe.
- You can reuse the same named result more than once.
- Each step can be tested alone by running just its inner
SELECT.
Several CTEs
WITH paid AS (
SELECT * FROM orders WHERE status = 'paid'
),
per_user AS (
SELECT user_id, SUM(total) AS spent FROM paid GROUP BY user_id
)
SELECT * FROM per_user WHERE spent > 500;Separate CTEs with a comma, and write WITH only once. A later CTE can use an earlier one.
NoteA CTE exists only for the one statement that follows it. Whether the database reuses its result or runs it again depends on the engine and its version, so do not assume a CTE caches anything.
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.