← All lessons
Combining and summarizing · Lesson 8 of 10

CTEs: queries in steps

Subqueries inside subqueries get hard to read quickly. A CTE (common table expression) lets you name a step with WITH name AS (…) and then use it like a table. The query reads top to bottom, one idea per step:

WITH order_totals AS (
  SELECT i.order_id, SUM(i.qty * p.price) AS total
  FROM order_items i
  JOIN products p ON p.id = i.product_id
  GROUP BY i.order_id
)
SELECT order_id, total
FROM order_totals
WHERE total > 80
ORDER BY total DESC;
Returns
order_id | total
---------+------
105      | 93.5
110      | 81.5
(2 rows)

Inside the CTE, the total is worked out with GROUP BY. Outside, it's just a column called total, so a plain WHERE can filter it.

You can have several CTEs, separated by commas, and each one can use the ones before it. Each customer's spending, built from the order totals:

WITH order_totals AS (
  SELECT i.order_id, SUM(i.qty * p.price) AS total
  FROM order_items i
  JOIN products p ON p.id = i.product_id
  GROUP BY i.order_id
),
customer_totals AS (
  SELECT o.customer_id, SUM(t.total) AS spent, COUNT(*) AS orders
  FROM orders o
  JOIN order_totals t ON t.order_id = o.id
  WHERE o.status = 'shipped'
  GROUP BY o.customer_id
)
SELECT c.name, ct.orders, ct.spent
FROM customer_totals ct
JOIN customers c ON c.id = ct.customer_id
ORDER BY ct.spent DESC;
Returns
name | orders | spent
-----+--------+------
Ana  | 3      | 106
Ben  | 2      | 99
Dev  | 1      | 93.5
Cleo | 1      | 81.5
Finn | 1      | 50
(5 rows)

Notice that joining order_totals to orders doesn't multiply anything: it has one row per order, so the order-level sum is safe. Building each step at the grain (the "one row per what") you need is the main way experienced people avoid the fan-out of the last lesson.

Build a CTE query one step at a time. Write the first CTE, then end with SELECT * FROM order_totals to check its rows. Only then add the next step.

For the database a CTE and a subquery are usually the same thing; most databases plan them alike. For people, the CTE is easier to read, test and change.

Practice

With a CTE called counts holding each customer_id and its number of orders, list the rows of counts where the number is above 1.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

WITH a AS (…) SELECT … FROM aName a step and use it like a table.
WITH a AS (…), b AS (…)Several steps; b can use a.
grainWhat one row stands for: one per order, per customer.

The other AI and data engineering courses