TheAnalyst / SQLAll lessons ↗
Day 16 · Advanced SQL · 10–20 minutes

Common table expressions

WITH gives a named result to a query, making multi-step logic easier to read.

01 · Learn

The idea

WITH gives a named result to a query, making multi-step logic easier to read. Read the query line by line and identify the input table, the transformation, and the shape of the result before running it.

WITH customer_totals AS (SELECT customer_id, SUM(amount) AS revenue FROM orders GROUP BY customer_id) SELECT customer_id, revenue FROM customer_totals WHERE revenue > 2500 ORDER BY revenue DESC;
Read it actively

Before running the example, predict the output columns and whether the query returns one row, many rows, or possibly no rows.

02 · Recall

Explain it without looking

In your own words, explain the main SQL feature in today’s lesson and why it answers the question.

03 · Solve

Run your own query

Use a CTE to calculate customer totals, then keep totals above 2500.

Loading browser SQL engine…
04 · Repeat

Close the loop