Naming a step with WITH
Subqueries in FROM get hard to read once they nest. A CTE (common table expression) does the
same job, but gives the step a name at the top of the query:
WITH per_customer AS (
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
)
SELECT AVG(order_count) AS avg_orders
FROM per_customerRead it top to bottom: first build per_customer, then use it. The result is exactly what the
subquery version in the last module gave, but each step now has a name you can talk about ("the
per-customer counts").
A CTE only exists while its query runs. It isn't saved in the database. (For a saved one, Tier 4 covers views.)