CTEs & Recursive CTEs
Your query for loyal buyers buried a GROUP BY inside a subquery inside a join, so you read it from the middle outward. The same logic can lay itself out top to bottom, one named step at a time.
- ▸Bury a
GROUP BYtwo layers deep and the query reads inside-out; name that layer and it reads straight down. - ▸A hierarchy walk is two halves: a starting row, and a step that re-runs against only the last pass's rows.
- ▸On a circular reporting line,
UNIONhalts only if no column changes per pass; alevelcounter keeps it looping.
Here are the spine tables again. users holds Ada(1), Brent(2), Cleo(3), Dane(4). orders carries rows tagged with user_id and an amount. The question: which users have spent more than 100 in total?
One way writes the per-user totals as a subquery dropped into the FROM:
SELECT u.name, t.total
FROM users u
JOIN (SELECT user_id, SUM(amount) AS total
FROM orders GROUP BY user_id) t
ON t.user_id = u.id
WHERE t.total > 100;To read it you start in the middle, decode the SUM and grouping, then climb back out to the join and the filter. The logic runs inside-out while your eye wants to run top-down.
Name that inner block instead. A WITH clause defines it once, above the main query, under a label:
WITH user_totals AS ( SELECT user_id, SUM(amount) AS total FROM orders GROUP BY user_id ) SELECT u.name, ut.total FROM users u JOIN user_totals ut ON ut.user_id = u.id WHERE ut.total > 100;
Same tables, same result rows. The named block is a common table expression, and the only thing that changed is reading order: the step that builds the totals now sits at the top with a name, and the main query reads it like any other table. Ask the database for the steps it takes to run each one, called its plan, and the two forms run the same plan.