×

sql · level 3 · unit 1 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

names a step so the rest of the query can use it.

Big questions are easier in steps. To find customers who spent over £50, first add up each customer's orders, then keep the big spenders. A subquery can do it, but queries nested inside queries soon get hard to read.

A , short for common table expression, gives a step a name. Write WITH spend AS ( ... ) before your main query, with any query inside the brackets. After that, spend works like a table, but only inside that one statement.

The main query then reads from the step. You read the whole thing top to bottom, like a recipe.

WITH spend AS (
  SELECT customer_id, SUM(total) AS spent
  FROM orders
  GROUP BY customer_id
)
SELECT c.name, s.spent
FROM spend AS s
JOIN customers AS c ON c.id = s.customer_id
WHERE s.spent > 50
ORDER BY s.spent DESC;

Professionals name each step after what it holds, so spend beats t1.