CTEs: write SQL in steps
A CTE lets you break a long query into named steps that read top to bottom. This guide goes from the first WITH to the patterns that turn up in data exams, take-homes and first jobs. Every box runs in your browser, and the practice questions check your answer. All the data is made up.
- Why stepsNested vs named
- The partsWITH, commas, final SELECT
- Build and checkOne step at a time
- 11 patternsWith Check buttons
- RefactorMessy to clean, same result
- Test and debugCounts, grain, fan-out
- Which tool whenCTE, subquery, temp table, Hex
- MockSix questions
The practice data: five made-up worlds
The same small database as SQL by example. A shop (customers, products, orders), a music app (listeners, artists, songs, streams), a football league (teams, matches), a phone app (app_users, events) and job offers (companies, offers, employees). The traps are on purpose: one order submitted twice, one event logged twice, a duplicate offer, missing values and postponed matches. Every Run starts from a fresh copy, so you cannot break anything.
1 Why write SQL in steps
Here is one question: which product categories earned more than the average category, counting delivered orders only and dropping the order that was submitted twice?
On the left it is written the way many people write it on their first go: queries inside queries. On the right it is the same logic as named steps with WITH. Run both.
Nested: read it inside out
Show the result without running
| category | revenue |
|---|---|
| Outdoor | 1742.0 |
| Kitchen | 967.0 |
Steps: read it top to bottom
Show the result without running
| category | revenue |
|---|---|
| Outdoor | 1742.0 |
| Kitchen | 967.0 |
Same result both ways: 2 rows, 2 columns.
Same answer. Now look at what the nested one makes you do:
- Read from the middle out. The first thing that happens (filter to delivered orders) is buried three levels deep.
- Write the same logic twice. The revenue calculation appears once for the list and again for the average. Change one and forget the other, and the answer is wrong with no error.
- Guess what
tandohold. Nothing tells you.
The CTE version reads like a recipe. Each step has a name that says what it holds, a comment that says what one row means, and you can stop at any step and look at it. That last part is the real win, and section 3 is built around it.
New to WITH? SQL from zero, section 15 introduces it in five minutes. Section 18 covers purpose comments and reconciling checks. This page goes further: patterns, refactoring, testing and when to use something else.
2 The parts of a CTE query
WITH step_one AS ( -- 1. WITH, once, at the very top
SELECT ...
FROM some_table
), -- 2. a comma between steps
step_two AS ( -- 3. no second WITH
SELECT ...
FROM step_one -- 4. a step can use any step above it
) -- 5. no comma after the last step
SELECT ... -- 6. the final SELECT is what you get back
FROM step_two;
Think of each step as a small table that lives only while the query runs. The final SELECT reads from them like any other table. Nothing is saved.
Rules worth knowing
- A step can only see steps above it. Order them the way the data flows.
- Names are scoped to the query. After the semicolon,
deliveredis gone. Run it again and it is rebuilt. - Use a step as often as you like. Section 1 used
category_revenuetwice: once for the rows, once for the average. - Name the columns inside each step.
SUM(x)with no alias gives the next step a column calledSUM(x). Always addAS. - You can name columns in the header instead:
WITH monthly(month, orders) AS (...). Handy, but less common. Pick one style. - ORDER BY inside a step does nothing useful. Sort in the final SELECT.
Three errors you will see
| You wrote | Error (SQLite) | Fix |
|---|---|---|
A comma after the last step: ... ), | near "SELECT": syntax error | Delete the last comma. |
WITH a AS (...), WITH b AS (...) | near "WITH": syntax error | One WITH. Commas after that. |
| A step uses one defined below it | no such table: b | Move it up. |
Music Average plays per listener, by plan
Predict first: Two plans, so how many rows? Will the listener who never streamed count?
Show the result without running
| plan | listeners | avg_plays |
|---|---|---|
| premium | 6 | 17.8 |
| free | 8 | 7.9 |
Two steps. Break it on purpose: add a comma after the closing bracket of plan_avg and run it. Then swap the two steps round. Read both errors, then press Reset.
The listener who never streamed is not in listener_plays at all, so the averages skip them. Whether that is right depends on the question. Mock question 2 comes back to it.
3 Build one step, check it, then the next
This is the habit that makes CTEs worth it. Do not write the whole query and press Run once at the end. Write step 1, look at it, then add step 2. Every bug is caught in the step that made it.
The question: for each premium listener, which artist did they play most? Count only full plays (30 seconds or more). Break ties by the lower artist_id.
1Write step 1. Count its rows.
Show the result without running
| rows_in_step |
|---|
| 165 |
Does the number look right? There are 170 streams in total, so full plays must be fewer. If you got 170, the filter is not working.
2Add step 2. Look at a few rows.
Show the result without running
| listener_id | artist_id | plays |
|---|---|---|
| 1 | 2 | 9 |
| 1 | 5 | 3 |
| 1 | 1 | 2 |
| 1 | 3 | 2 |
| 1 | 4 | 1 |
| 2 | 2 | 3 |
| 2 | 7 | 2 |
| 2 | 1 | 1 |
| 2 | 5 | 1 |
| 3 | 2 | 13 |
| 3 | 7 | 2 |
| 3 | 5 | 1 |
Check the grain: listener_id and artist_id together should never repeat. Eyeball the first listener: do the plays look sensible?
3Add step 3. Look at one or two listeners in full.
Show the result without running
| listener_id | artist_id | plays | rn |
|---|---|---|---|
| 1 | 2 | 9 | 1 |
| 1 | 5 | 3 | 2 |
| 1 | 1 | 2 | 3 |
| 1 | 3 | 2 | 4 |
| 1 | 4 | 1 | 5 |
| 2 | 2 | 3 | 1 |
| 2 | 7 | 2 | 2 |
| 2 | 1 | 1 | 3 |
| 2 | 5 | 1 | 4 |
Filtering to two listeners makes the ranking easy to check by eye. If two artists tie on plays, the lower artist_id should get rn = 1.
4Add the final SELECT.
Show the result without running
| listener | top_artist | plays |
|---|---|---|
| Ada | Mara Vale | 9 |
| Cara | Mara Vale | 13 |
| Finn | Mara Vale | 12 |
| Hugo | Mara Vale | 5 |
| Kai | Mara Vale | 7 |
| Nora | The Gannets | 3 |
Only now do names and the premium filter come in. If a premium listener were missing, you would go back one step and look for them there.
Notice the final SELECT changes at every step, but the steps above it only grow. While you build, the last line is a window you point at whichever step you are checking. When you are done, it becomes the answer.
4 Eleven patterns that come up again and again
Each one has a template, two or three worked examples on different data, the usual mistake, and a question for you with a Check button. Check runs your query and a hidden answer and compares the results. Column names do not have to match unless the question names them; values and row counts do.
Open them one at a time. The first is open already.
1Clean, then aggregate
Put all the cleaning in step 1: drop bad rows, remove duplicates, fill blanks. Every later step can then trust the data.
WITH clean AS ( -- one row per real record
SELECT DISTINCT ... -- de-dupe
FROM raw_table
WHERE ... -- drop rows you never want
)
SELECT group_col, COUNT(*), SUM(...)
FROM clean
GROUP BY group_col;Examples
Shop Revenue after discount per category
Predict first: What happens to net revenue for an order whose discount is NULL if you skip COALESCE?
Show the result without running
| category | net_revenue |
|---|---|
| Games | 158.45 |
| Books | 153.92 |
| Kitchen | -1707.0 |
| Outdoor | -2659.0 |
Three cleaning jobs in one place: the duplicate order goes, cancelled orders go, and a missing discount becomes 0 so the maths does not turn into NULL.
Music Full plays per artist
Show the result without running
| artist | full_plays |
|---|---|
| Mara Vale | 66 |
| The Gannets | 27 |
| Neon Curlew | 22 |
| Driftwood Kids | 21 |
| Low Kettle | 21 |
| Brass Harbour | 4 |
| Sally Gap | 4 |
The rule for what counts as a play lives in one place. If the rule changes to 60 seconds, you change one number.
App Events per type, with the double-logged row removed
Show the result without running
| event_name | events | users |
|---|---|---|
| session_start | 93 | 33 |
| signup | 36 | 36 |
| onboarding_done | 30 | 30 |
| first_post | 17 | 17 |
| subscribe | 10 | 10 |
onboarding_done drops by one against the raw table. DISTINCT across every column except the ID is the quickest de-dupe when the copy is exact.
Common mistake
Cleaning in the final SELECT, after a join. By then a duplicate row may have been joined to other rows and multiplied. Clean first.
Try it yourself
Jobs Average accepted salary per job family, rounded to a whole number. Remove the duplicate offer (same company, family, level, salary and date) and skip missing salaries. Columns:
job_family,avg_salary.Hint
Step 1: SELECT DISTINCT company_id, job_family, level, base_salary, offered_at from accepted offers with a salary. Then GROUP BY job_family.
Show the answer
2Aggregate, then filter (instead of HAVING)
Work out the totals in one step, then filter them with a plain WHERE. Same result as HAVING, and you can reuse the total.
WITH totals AS (
SELECT key, SUM(x) AS total
FROM t
GROUP BY key
)
SELECT key, total
FROM totals
WHERE total > 100;Examples
Shop Customers who spent over 200 on delivered orders
HAVING
Show the result without running
| customer_id | spend |
|---|---|
| 3 | 674.0 |
| 9 | 440.49 |
| 13 | 311.5 |
| 5 | 280.47 |
| 12 | 254.99 |
| 10 | 248.0 |
| 15 | 222.0 |
| 1 | 215.97 |
| 16 | 202.0 |
CTE, then WHERE
Show the result without running
| customer_id | spend |
|---|---|
| 3 | 674.0 |
| 9 | 440.49 |
| 13 | 311.5 |
| 5 | 280.47 |
| 12 | 254.99 |
| 10 | 248.0 |
| 15 | 222.0 |
| 1 | 215.97 |
| 16 | 202.0 |
Same result both ways: 9 rows, 2 columns.
Music Songs played by at least 5 different listeners, with a label
Show the result without running
| title | listeners | reach |
|---|---|---|
| Glass Tide | 11 | wide |
| Salt Road | 9 | wide |
| Wild Garlic | 9 | wide |
| Wren Song | 8 | wide |
| Ferry Home | 7 | steady |
| Long Grass | 7 | steady |
| Copper Sky | 6 | steady |
| Night Bus | 6 | steady |
| Paper Moon | 6 | steady |
| Blue Hour | 5 | steady |
| Half Light | 5 | steady |
| Iron Bridge | 5 | steady |
| Kite Weather | 5 | steady |
The count is used three times: to filter, to label and to sort. With HAVING you would write COUNT(DISTINCT listener_id) out each time.
Football Teams that scored 8 or more at home
Show the result without running
| name | goals |
|---|---|
| Harbour United | 12 |
Postponed matches have NULL goals. SUM skips NULLs anyway, but filtering them out says so in writing.
Common mistake
Putting an aggregate in WHERE in the same SELECT that makes it: WHERE SUM(x) > 200. WHERE runs before grouping, so the total does not exist yet. Use HAVING, or a CTE and WHERE.
Try it yourself
App Countries with at least 5 app users. Columns:
country,users.Hint
One step counts users per country. The final SELECT keeps users >= 5.
Show the answer
3Join two totals at different grains
When one parent has two lists of children, total each list in its own step first. Join the totals, never the raw rows.
WITH a_totals AS (SELECT key, COUNT(*) AS a FROM child_a GROUP BY key),
b_totals AS (SELECT key, COUNT(*) AS b FROM child_b GROUP BY key)
SELECT p.key, a.a, b.b
FROM parent AS p
LEFT JOIN a_totals AS a ON a.key = p.key
LEFT JOIN b_totals AS b ON b.key = p.key;Examples
Music Songs and plays per artist
Wrong: join the raw rows, then count
Show the result without running
| name | songs | plays |
|---|---|---|
| Brass Harbour | 4 | 4 |
| Driftwood Kids | 21 | 21 |
| Low Kettle | 22 | 22 |
| Mara Vale | 67 | 67 |
| Neon Curlew | 24 | 24 |
| Sally Gap | 4 | 4 |
| The Gannets | 28 | 28 |
Right: total each list, then join
Show the result without running
| name | songs | plays |
|---|---|---|
| Brass Harbour | 2 | 4 |
| Driftwood Kids | 3 | 21 |
| Low Kettle | 2 | 22 |
| Mara Vale | 4 | 67 |
| Neon Curlew | 3 | 24 |
| Quiet Pylon | 1 | 0 |
| Sally Gap | 2 | 4 |
| The Gannets | 3 | 28 |
On the left, songs equals plays for every artist. After the join there is one row per play, so counting song IDs counts plays. COUNT(DISTINCT s.song_id) would patch this one, but it cannot patch a SUM. The right-hand version is correct by design.
Football Goals scored per team, home and away
Wrong: join the raw rows, then count
Show the result without running
| name | home_goals | away_goals |
|---|---|---|
| Bogside Athletic | 30 | 15 |
| Claddagh Town | 35 | 40 |
| Harbour United | 60 | 30 |
| Northside Wanderers | 10 | 15 |
| Riverside Rovers | 35 | 55 |
| Shannon Celtic | 20 | 15 |
Right: total each list, then join
Show the result without running
| name | home_goals | away_goals |
|---|---|---|
| Bogside Athletic | 6 | 3 |
| Claddagh Town | 7 | 8 |
| Harbour United | 12 | 6 |
| Northside Wanderers | 2 | 3 |
| Riverside Rovers | 7 | 11 |
| Shannon Celtic | 4 | 3 |
Every home match is paired with every away match, so each home goal is counted once per away match. The numbers on the left are several times too big, and nothing errors. This is the most common silent bug in exam answers.
Common mistake
Fixing fan-out with DISTINCT on the final result. SUM(DISTINCT goals) also drops two genuine matches that happen to have the same score. Fix the grain, not the symptom.
Try it yourself
Jobs For each job family: how many offers and how many employees. Columns:
job_family,offers,employees.Hint
Two steps, each GROUP BY job_family: one on offers, one on employees. Join the two on job_family.
Show the answer
4Latest row per group
Number the rows inside each group with ROW_NUMBER in a CTE, newest first. Then keep row 1.
WITH ranked AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY group_key
ORDER BY event_date DESC, id DESC -- tie-break
) AS rn
FROM t
)
SELECT * FROM ranked WHERE rn = 1;Examples
Shop Each customer's most recent order
Predict first: 18 customers ordered. How many rows?
Show the result without running
| name | order_id | order_date | status |
|---|---|---|---|
| Saoirse Doyle | 69 | 2025-06-24 | delivered |
| Conor Foley | 68 | 2025-06-17 | delivered |
| Oisin Ryan | 66 | 2025-06-14 | delivered |
| Roisin Quinn | 67 | 2025-06-14 | delivered |
| Eoin Murphy | 65 | 2025-06-13 | delivered |
| Ciara Brennan | 64 | 2025-06-11 | returned |
| Aisling Keane | 63 | 2025-06-09 | delivered |
| Aoife Byrne | 61 | 2025-06-04 | delivered |
| Darragh Nolan | 58 | 2025-06-01 | delivered |
| Grainne Lynch | 59 | 2025-06-01 | returned |
| Niamh Kelly | 56 | 2025-05-14 | delivered |
| Fionn Daly | 55 | 2025-05-13 | delivered |
| Tadhg Burke | 53 | 2025-05-10 | delivered |
| Orla Kavanagh | 54 | 2025-05-10 | delivered |
| Cian Walsh | 50 | 2025-04-28 | cancelled |
| Sinead Moran | 43 | 2025-04-14 | returned |
| Ronan Duffy | 30 | 2025-03-03 | delivered |
| Padraig Healy | 13 | 2025-01-28 | delivered |
You cannot write WHERE ROW_NUMBER() ... = 1 directly. Window functions run after WHERE. The CTE gives the number a name so the next step can filter on it.
Jobs The latest offer at each company
Show the result without running
| name | job_family | offered_at |
|---|---|---|
| Umberfield Software | Product | 2024-12-29 |
| Saltmarsh Stores | Data | 2024-12-21 |
| Glenvarra Energy | Engineering | 2024-09-29 |
| Brightwell Analytics | Design | 2024-09-22 |
| Kettlebrook Bank | Engineering | 2024-09-08 |
| Harbourlight Health | Data | 2024-08-29 |
| Pixelmoor Games | Sales | 2024-05-07 |
| Larkspur Freight | Product | 2024-04-08 |
| Copperleaf Foods | Engineering | 2024-02-09 |
| Willowby Insurance | Product | 2023-07-25 |
| Quillstone Media | Product | 2023-03-18 |
Zillmere Robotics made no offers, so it is not here. If the question says every company, start from companies and LEFT JOIN.
Football Each team's last played match
Show the result without running
| name | match_date | scored | conceded |
|---|---|---|---|
| Bogside Athletic | 2024-09-28 | 0 | 3 |
| Claddagh Town | 2024-09-21 | 2 | 1 |
| Harbour United | 2024-09-21 | 1 | 1 |
| Northside Wanderers | 2024-09-14 | 1 | 3 |
| Riverside Rovers | 2024-09-28 | 1 | 2 |
| Shannon Celtic | 2024-09-28 | 2 | 1 |
Three steps: turn each match into two team rows, drop postponed games, then rank. Each step does one job, so each can be checked alone.
Common mistake
Leaving out the tie-break. Two orders on the same day get row numbers in whatever order the database likes, and your answer can change between runs.
Try it yourself
Music Each listener's most recent stream. If two are on the same day, take the higher stream_id. Columns:
listener_id,song_id,streamed_on.Hint
ROW_NUMBER() OVER (PARTITION BY listener_id ORDER BY streamed_on DESC, stream_id DESC) in a CTE. Keep rn = 1.
Show the answer
5Compare each row to its group average
Work out the average per group in one step, join it back to the rows, then compare.
WITH group_avg AS (
SELECT grp, AVG(x) AS avg_x
FROM t
GROUP BY grp
)
SELECT t.*, g.avg_x, t.x - g.avg_x AS diff
FROM t
JOIN group_avg AS g ON g.grp = t.grp;Examples
Shop Products priced above their category's average
Predict first: Four categories. At least how many products must be above their own average?
Show the result without running
| name | category | price | category_avg |
|---|---|---|---|
| Atlas of Islands | Books | 38.0 | 25.66 |
| Board Game: Harbour | Games | 34.99 | 21.83 |
| Coffee Grinder | Kitchen | 75.0 | 58.67 |
| Chef Knife | Kitchen | 59.0 | 58.67 |
| Rain Jacket | Outdoor | 120.0 | 84.83 |
| Trail Runner Shoes | Outdoor | 89.0 | 84.83 |
Join back on the group key. The average is worked out once per category, not once per product.
Jobs Each accepted offer against its family's average
Show the result without running
| offer_id | job_family | base_salary | vs_family_avg |
|---|---|---|---|
| 45 | Product | 92000 | 34611.0 |
| 26 | Data | 83000 | 27273.0 |
| 44 | Data | 75000 | 19273.0 |
| 43 | Design | 74000 | 18875.0 |
| 5 | Data | 74000 | 18273.0 |
| 10 | Product | 73500 | 16111.0 |
| 41 | Design | 68500 | 13375.0 |
| 37 | Design | 68000 | 12875.0 |
The filter appears twice, once in the step and once at the end. That repetition is a hint the filter wants its own step. Try moving it into an accepted CTE that both parts read from.
Music Same idea with a window function
Show the result without running
| title | artist_id | length_sec | artist_avg |
|---|---|---|---|
| Salt Road | 1 | 265 | 223.0 |
| Paper Moon | 2 | 305 | 225.0 |
| Glass Tide | 2 | 249 | 225.0 |
| Copper Sky | 3 | 259 | 206.0 |
| Tin Roof | 4 | 159 | 156.0 |
| Harbour Lights | 5 | 207 | 195.0 |
| Blue Hour | 5 | 207 | 195.0 |
| Static Bloom | 6 | 218 | 205.0 |
| Last Tram | 7 | 310 | 262.0 |
| Iron Bridge | 7 | 300 | 262.0 |
AVG() OVER (PARTITION BY ...) puts the group average on every row without a join. You still need the CTE, because you cannot filter on a window function in the same SELECT.
Common mistake
Comparing to the overall average when the question says their group. Read the question for the word that names the group.
Try it yourself
Jobs Accepted offers whose salary is above the average accepted salary for their level. Skip missing salaries. Columns:
offer_id,level,base_salary.Hint
A CTE of AVG(base_salary) per level from accepted offers with a salary. Join it back on level and keep base_salary > the average.
Show the answer
6Funnel step counts
Make one row per user with a 0/1 flag for each step. Then add up the flags.
WITH user_steps AS ( -- one row per user
SELECT user_id,
MAX(CASE WHEN event_name = 'a' THEN 1 ELSE 0 END) AS did_a,
MAX(CASE WHEN event_name = 'b' THEN 1 ELSE 0 END) AS did_b
FROM events
GROUP BY user_id
)
SELECT SUM(did_a), SUM(did_b) FROM user_steps;Examples
App The four-step funnel
Predict first: 36 users signed up. Will onboarded be 30 or 31?
Show the result without running
| signed_up | onboarded | posted | subscribed |
|---|---|---|---|
| 36 | 30 | 17 | 10 |
MAX of a 0/1 flag means did it at least once. That quietly handles the double-logged onboarding row too.
App Funnel by platform, with conversion
Show the result without running
| platform | users | onboarded | subscribed | pct_subscribed |
|---|---|---|---|---|
| ios | 9 | 9 | 4 | 44.4 |
| android | 16 | 14 | 5 | 31.3 |
| web | 11 | 7 | 1 | 9.1 |
Three steps: flags per user, counts per platform, then the percentage. Writing the percentage in its own step means you never divide inside a SUM by mistake.
Common mistake
Counting events instead of users. COUNT(*) of onboarding events gives 31 because one was logged twice. A funnel counts people.
Try it yourself
App For each platform: users who finished onboarding and users who made a first post. Count people, not events. Columns:
platform,onboarded,posted.Hint
Flags per user with MAX(CASE ...), join to app_users for the platform, then SUM the flags per platform.
Show the answer
7Month over month with LAG
Total per month in one step. In the next, LAG pulls last month's total onto this month's row so you can subtract.
WITH monthly AS (
SELECT strftime('%Y-%m', d) AS month, SUM(x) AS total
FROM t
GROUP BY month
)
SELECT month, total,
total - LAG(total) OVER (ORDER BY month) AS change
FROM monthly;Examples
Shop Delivered revenue per month and the change
Predict first: Which month will have NULL in every change column?
Show the result without running
| month | revenue | change | pct_change |
|---|---|---|---|
| 2025-01 | 613.99 | NULL | NULL |
| 2025-02 | 320.99 | -293.0 | -47.7 |
| 2025-03 | 418.43 | 97.44 | 30.4 |
| 2025-04 | 991.0 | 572.57 | 136.8 |
| 2025-05 | 899.5 | -91.5 | -9.2 |
| 2025-06 | 490.47 | -409.03 | -45.5 |
January has no previous month, so its change is NULL. That is correct. Do not turn it into 0: nothing changed is a different claim from there is nothing to compare.
Music Full plays per week in March
Show the result without running
| week_from | full_plays | change |
|---|---|---|
| 2025-03-01 | 12 | NULL |
| 2025-03-03 | 41 | 29 |
| 2025-03-10 | 42 | 1 |
| 2025-03-17 | 41 | -1 |
| 2025-03-24 | 29 | -12 |
The week number is the group key. MIN(streamed_on) gives a readable label. The first week is partial, so read its change with care.
Common mistake
Putting LAG and GROUP BY in the same SELECT and getting confused about which runs first. Keep them in separate steps: total first, then compare.
Try it yourself
Shop Orders per month (every row in the orders table), the previous month's count and the change. Sorted by month. Columns:
month,orders,prev_orders,change.Hint
Step 1: strftime('%Y-%m', order_date) AS month, COUNT(*) GROUP BY month. Final SELECT: LAG(orders) OVER (ORDER BY month).
Show the answer
8Percent of total
One step for the parts, one step for the total, then divide. Multiply by 100.0, not 100, so SQLite does not round to a whole number.
WITH parts AS (SELECT grp, SUM(x) AS part FROM t GROUP BY grp),
total AS (SELECT SUM(part) AS total FROM parts)
SELECT grp, ROUND(100.0 * part / total, 1) AS pct
FROM parts CROSS JOIN total;Examples
Shop Each category's share of delivered revenue
Predict first: Roughly what should the four percentages add up to?
Show the result without running
| category | revenue | pct_of_total |
|---|---|---|
| Outdoor | 1742.0 | 46.6 |
| Kitchen | 967.0 | 25.9 |
| Books | 686.93 | 18.4 |
| Games | 338.45 | 9.1 |
The total is built from the parts, so the percentages add to 100 by construction. CROSS JOIN with a one-row step puts the total on every row.
Music Listeners by country, missing country included
Show the result without running
| country | listeners | pct |
|---|---|---|
| IE | 5 | 33.3 |
| UK | 4 | 26.7 |
| FR | 3 | 20.0 |
| DE | 2 | 13.3 |
| unknown | 1 | 6.7 |
SUM(...) OVER () with empty brackets is the grand total on every row. Shorter than a total step. Use whichever you can explain.
Common mistake
100 * part / total with whole numbers in SQLite gives whole-number division: 7 out of 45 becomes 15, not 15.6. Use 100.0.
Try it yourself
Jobs Each industry's share of all offers, as a percentage rounded to 1 decimal place. Columns:
industry,offers,pct.Hint
Join offers to companies, count per industry, then divide by the total with 100.0.
Show the answer
9Find and remove duplicates
Step 1 finds the copies. Step 2 numbers each set of copies with ROW_NUMBER. Keep row 1.
WITH numbered AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY col_a, col_b, col_c -- what makes a copy
ORDER BY id -- keep the first
) AS rn
FROM t
)
SELECT * FROM numbered WHERE rn = 1;Examples
Shop Find the order submitted twice
Show the result without running
| customer_id | product_id | quantity | order_date | copies | first_id | last_id |
|---|---|---|---|---|---|---|
| 5 | 5 | 2 | 2025-04-08 | 2 | 41 | 70 |
Look before you delete. Decide which columns make two rows the same thing. Here it is everything except order_id.
Jobs Keep one of each duplicate offer
Show the result without running
| offers_before | offers_after |
|---|---|
| 45 | 44 |
45 rows become 44. ROW_NUMBER is better than DISTINCT when you need to keep the ID column, or choose which copy to keep.
Common mistake
De-duping on too few columns. PARTITION BY company_id alone would keep one offer per company and throw away real data. Write down what makes two rows the same thing first.
Try it yourself
App Events per event name after removing exact copies (same user, name and time). Columns:
event_name,events.Hint
ROW_NUMBER() OVER (PARTITION BY user_id, event_name, event_time ORDER BY event_id), keep rn = 1, then count per event_name.
Show the answer
10Cohorts and repeat rate
Give each person a start month in step 1. Join that back to their activity in step 2. Count per start month in step 3.
WITH first_seen AS (
SELECT person_id, MIN(month) AS cohort
FROM activity GROUP BY person_id
),
later AS (
SELECT DISTINCT a.person_id, f.cohort
FROM activity AS a JOIN first_seen AS f USING (person_id)
WHERE a.month > f.cohort
)
SELECT cohort, COUNT(*) ... ;Examples
Shop Customers by first order month, and how many came back
Predict first: Which cohort has had the most time to come back?
Show the result without running
| cohort | customers | came_back | pct_came_back |
|---|---|---|---|
| 2025-01 | 9 | 8 | 88.9 |
| 2025-02 | 3 | 3 | 100.0 |
| 2025-03 | 3 | 2 | 66.7 |
| 2025-04 | 3 | 3 | 100.0 |
Later cohorts have had less time to come back, so their rates look worse. Say so when you present a table like this.
App Signup month and active the next month
Show the result without running
| cohort | users | active_next_month |
|---|---|---|
| 2025-01 | 12 | 10 |
| 2025-02 | 12 | 10 |
| 2025-03 | 12 | 10 |
date('2025-01-01', '+1 month') moves a date on a month in SQLite. In Hex on DuckDB you would write cohort + INTERVAL 1 MONTH.
Common mistake
Counting cohort size from the activity table instead of the people table. People who signed up and did nothing vanish, and every rate looks better than it is.
Try it yourself
App For each signup month: number of users, number who ever subscribed, and the percentage rounded to 1 place. Columns:
cohort,users,subscribed,pct.Hint
Cohort from app_users. A second step with the DISTINCT user_ids that have a subscribe event. LEFT JOIN, count, then 100.0 * ... / ...
Show the answer
11Top N per group
Total per item in one step, rank inside each group in the next, keep rank <= N.
WITH totals AS (SELECT grp, item, SUM(x) AS total FROM t GROUP BY grp, item),
ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY grp ORDER BY total DESC, item) AS rn
FROM totals
)
SELECT * FROM ranked WHERE rn <= 3;Examples
Music Top 2 songs per artist by full plays
Show the result without running
| artist | title | full_plays | rn |
|---|---|---|---|
| Brass Harbour | Tin Roof | 3 | 1 |
| Brass Harbour | Slow Rain | 1 | 2 |
| Driftwood Kids | Wren Song | 11 | 1 |
| Driftwood Kids | Iron Bridge | 7 | 2 |
| Low Kettle | Copper Sky | 14 | 1 |
| Low Kettle | Night Bus | 7 | 2 |
| Mara Vale | Glass Tide | 29 | 1 |
| Mara Vale | Ferry Home | 17 | 2 |
| Neon Curlew | Wild Garlic | 10 | 1 |
| Neon Curlew | Blue Hour | 8 | 2 |
| Sally Gap | Hollow Hill | 3 | 1 |
| Sally Gap | Static Bloom | 1 | 2 |
| The Gannets | Salt Road | 14 | 1 |
| The Gannets | Kite Weather | 7 | 2 |
Want ties to share a place? Swap ROW_NUMBER for RANK, and an artist can show three songs. Say which you chose and why.
Jobs Two highest accepted salaries in each job family
Show the result without running
| job_family | offer_id | base_salary | salary_rank |
|---|---|---|---|
| Data | 26 | 83000 | 1 |
| Data | 44 | 75000 | 2 |
| Design | 43 | 74000 | 1 |
| Design | 41 | 68500 | 2 |
| Engineering | 15 | 69000 | 1 |
| Engineering | 30 | 63500 | 2 |
| Product | 45 | 92000 | 1 |
| Product | 10 | 73500 | 2 |
| Sales | 9 | 42500 | 1 |
| Sales | 38 | 42000 | 2 |
DENSE_RANK means the two highest distinct salaries. If two offers share the top salary, both appear, and so does the next salary down.
Common mistake
ORDER BY ... LIMIT 2 gives the top 2 overall, not per group. LIMIT has no idea what a group is.
Try it yourself
Shop The top 2 products in each category by units sold on delivered orders. Break ties by the lower product_id. Columns:
category,name,units.Hint
SUM(quantity) per product from delivered orders, then ROW_NUMBER() OVER (PARTITION BY category ORDER BY units DESC, product_id). Keep rn <= 2.
Show the answer
Want more of these? SQL by example has 28 patterns on the same practice data, many of them written with CTEs.
5 Refactoring: from nested to named steps
Real queries arrive messy, often from a colleague or from an AI tool. Refactoring means rewriting them into steps without changing the result. The method is the same every time:
- Run the original and note the row count and a few values.
- Find the innermost subquery. Lift it into the first CTE. Give it a name that says what it holds.
- Replace it in the original with the name. Run again. Same result?
- Repeat, working outwards, until the final SELECT is short.
- Look for logic written twice. Make it one step that both parts read from.
Each pair below gives the same result. The build of this page checks that every pair matches, row for row.
Music Refactor 1: Average full plays per listener, by plan
Before
Show the result without running
| plan | avg_full_plays |
|---|---|
| free | 7.6 |
| premium | 17.3 |
After
Show the result without running
| plan | avg_full_plays |
|---|---|
| free | 7.6 |
| premium | 17.3 |
Same result both ways: 2 rows, 2 columns.
Straight lift-out, innermost first. x became full_plays. Nothing else changed, which is the point: refactor first, improve second.
Jobs Refactor 2: Companies with more accepted offers than the average company
Before
Show the result without running
| name | accepted |
|---|---|
| Saltmarsh Stores | 7 |
| Copperleaf Foods | 5 |
| Harbourlight Health | 5 |
| Larkspur Freight | 4 |
| Umberfield Software | 4 |
After
Show the result without running
| name | accepted |
|---|---|
| Saltmarsh Stores | 7 |
| Copperleaf Foods | 5 |
| Harbourlight Health | 5 |
| Larkspur Freight | 4 |
| Umberfield Software | 4 |
Same result both ways: 5 rows, 2 columns.
The original counts accepted offers three times in three places. The refactor counts once. Watch the subtle part: the average is over companies with an accepted offer, in both versions. If the question meant all 12 companies, that is a bug to raise, not to fix silently while refactoring.
App Refactor 3: Users who signed up in February and posted within 7 days
Before
Show the result without running
| user_id | platform |
|---|---|
| 14 | ios |
| 15 | ios |
| 16 | android |
| 17 | android |
After
Show the result without running
| user_id | platform |
|---|---|
| 14 | ios |
| 15 | ios |
| 16 | android |
| 17 | android |
Same result both ways: 4 rows, 2 columns.
The correlated subquery (the one that looks up the signup date for each event) disappears once both sides are steps and you join them. DISTINCT keeps the IN behaviour: a user with two posts still appears once.
Your turn
Shop Rewrite this as CTEs. Your result must match it exactly.
SELECT c.name, s.spend FROM customers c JOIN (SELECT o.customer_id, SUM(o.quantity * p.price) AS spend FROM orders o JOIN products p ON p.product_id = o.product_id WHERE o.status = 'delivered' GROUP BY o.customer_id) s ON s.customer_id = c.customer_id WHERE s.spend > (SELECT AVG(spend) FROM (SELECT SUM(o.quantity * p.price) AS spend FROM orders o JOIN products p ON p.product_id = o.product_id WHERE o.status = 'delivered' GROUP BY o.customer_id));Hint
The spend-per-customer subquery is written twice. Make it one CTE called customer_spend. The average is then
(SELECT AVG(spend) FROM customer_spend).Show the answer
The wrong answer most people write first: taking the average over order lines instead of over customers. Both look reasonable. Only one matches the original.
6 Testing and debugging CTEs
A query that runs is not a query that is right. These four checks take a minute each and catch nearly every bug in an exam answer. SQL from zero, section 18 adds a fifth: check that the parts add up to a total you can get another way.
1. Row counts per step
Keep the steps. Swap the final SELECT for a count of each one, joined with UNION ALL. You see at a glance where rows appear or vanish.
Shop How many rows does each step keep?
Predict first: Write your four numbers down before you run it.
Show the result without running
| step | n_rows |
|---|---|
| orders | 70 |
| not_cancelled | 65 |
| deduped | 64 |
| with_product | 64 |
70, then 65 (5 cancelled), then 64 (one copy gone), then 64 (every order has a product). If the join step had shown 63 or 80, you would know exactly which step to look at.
2. Grain check
Write the grain as a comment: -- one row per customer. Then prove it. If COUNT(*) equals COUNT(DISTINCT key), the key is unique and the comment is true.
Music Is listener_artist really one row per listener and artist?
Show the result without running
| n_rows | n_keys |
|---|---|
| 62 | 62 |
Equal, so the grain holds. Joining two columns with a dash makes a single key to count. Now delete s.artist_id from the GROUP BY and run it again: the numbers change and the comment is no longer true.
3. The fan-out check
Before any join, count rows on the side you care about. After the join, count again. If the number went up and you did not expect it to, the join is multiplying rows.
Football Does joining home and away matches multiply rows?
Show the result without running
| home_rows | rows_after_join |
|---|---|
| 30 | 150 |
30 home rows become 150. That is the fan-out from pattern 3, caught with one line instead of by staring at goal totals.
4. Point the final SELECT at a middle step
When the answer looks wrong, do not rewrite. Leave every step in place and change only the last line to look inside one of them. Work backwards until the data looks right; the bug is in the step after that.
App Why is a user missing from the funnel?
Show the result without running
| user_id | signed_up | subscribed |
|---|---|---|
| 7 | 1 | 1 |
| 12 | 1 | 1 |
| 14 | 1 | 1 |
| 16 | 1 | 1 |
| 25 | 1 | 1 |
| 28 | 1 | 1 |
| 30 | 1 | 1 |
| 31 | 1 | 1 |
| 33 | 1 | 1 |
| 36 | 1 | 1 |
Comment out the real final SELECT with --, look at the step, then swap back. In Hex, the same trick is a scratch cell under the query; delete it before you share.
Checklist before you submit
- Every step has a grain comment, and you checked it.
- You know the row count after every join, and why it is what it is.
- Every LEFT JOIN that feeds a COUNT or SUM uses COALESCE where zero is the right answer.
- Every ROW_NUMBER has a tie-break.
- No scratch SELECTs left at the bottom.
7 CTE, subquery, temp table or Hex cells?
| Tool | Use it when | Watch out for |
|---|---|---|
| CTE | Two or more steps. Any step used twice. Anything you will hand in or share. | Lives for one statement only. Some older databases run a CTE again each time you use it. |
| Subquery | One short lookup: WHERE x > (SELECT AVG(x) FROM t) or IN (SELECT id ...). | Once it nests two deep, lift it into a CTE. |
| Temp table | A slow step you want to reuse across several queries in one session, or check once and stop recomputing. | It is real: it stays until the session ends. Name clashes. Not allowed in many exam tools. |
| Hex chained cells | Working and exploring. Each SQL cell's result becomes a dataframe the next cell can query. | Cells rerun by what depends on what, not by position. Hard for a grader to rerun in one go. |
A temp table, runnable here
Same idea as a CTE, but it is saved for the rest of the session. Here the box runs both statements together.
Make it once, query it twice
Show the result without running
| customers | avg_spend | top_spend |
|---|---|---|
| 18 | 207.47 | 674.0 |
On this page every Run starts from a fresh database, so the temp table never clashes. In a real session, run the CREATE twice and you get an error: the table already exists.
Hex: chain cells while you work, fold into one CTE to submit
In Hex, each SQL cell has an output name. A later SQL cell can query it as if it were a table. That is a CTE spread across cells, and it is a lovely way to work, because every step shows its result as you go.
While you work: three cells
-- Cell 1, output named: delivered
SELECT DISTINCT customer_id, product_id,
quantity, order_date
FROM orders
WHERE status = 'delivered'
-- Cell 2, output named: category_revenue
SELECT p.category,
SUM(d.quantity * p.price) AS revenue
FROM delivered AS d
JOIN products AS p
ON p.product_id = d.product_id
GROUP BY p.category
-- Cell 3
SELECT *
FROM category_revenue
ORDER BY revenue DESCTo submit: one cell
WITH delivered AS (
SELECT DISTINCT customer_id, product_id,
quantity, order_date
FROM orders
WHERE status = 'delivered'
),
category_revenue AS (
SELECT p.category,
SUM(d.quantity * p.price) AS revenue
FROM delivered AS d
JOIN products AS p
ON p.product_id = d.product_id
GROUP BY p.category
)
SELECT *
FROM category_revenue
ORDER BY revenue DESCFolding is mechanical: each cell's SQL goes inside name AS ( ... ), using the cell's output name as the CTE name. Then run the single version and check it matches the last chained cell. One cell is easier to grade, easier to paste into a write-up, and it cannot be broken by cells running out of order.
One trap: a dataframe SQL cell in Hex runs on DuckDB, while a cell pointed at a warehouse uses that warehouse's SQL. The CTE syntax is the same in both. Date functions are not. The Hex section of SQL by example lists the differences.
Optional: recursive CTEs
A recursive CTE refers to itself. It starts with one row and keeps adding rows until a condition stops it. You will rarely need one in an exam, but two jobs come up: filling in missing dates and walking a hierarchy.
Music Every day in March, including days with no plays
Show the result without running
| day | plays |
|---|---|
| 2025-03-31 | 0 |
| 2025-03-30 | 0 |
| 2025-03-29 | 0 |
| 2025-03-28 | 8 |
| 2025-03-27 | 4 |
| 2025-03-26 | 5 |
| 2025-03-25 | 6 |
| 2025-03-24 | 7 |
The data stops on 28 March. Without the date series, 29 to 31 March would simply be missing from a chart, and the line would not drop to zero. With it, they show as 0.
Walk up a manager chain (a small made-up org chart)
Show the result without running
| depth | name |
|---|---|
| 0 | Analyst |
| 1 | Senior Analyst |
| 2 | Analytics Lead |
| 3 | Head of Data |
Each round finds the manager of the last person found. It stops when manager_id is NULL. Always make sure there is a stop, or the query runs forever.
In Postgres, Snowflake and DuckDB you write WITH RECURSIVE the same way. SQL Server leaves out the word RECURSIVE. BigQuery supports it too.
8 Mock: six CTE questions
Give yourself 40 minutes. Build each one a step at a time, check each step, then press Check. Every question has a trap from this page in it.
Shop For each city, how many customers placed at least one delivered order? Include customers with no city as their own group. Columns:
city,customers.Hint
Step 1: DISTINCT customer_id from delivered orders. Join to customers and count per city.
Show the answer
Music Average full plays (30+ seconds) per listener for each plan, rounded to 1 place. Listeners with no full plays count as 0. Columns:
plan,avg_full_plays.Hint
Count full plays per listener in a CTE. Start the final query from listeners and LEFT JOIN, with COALESCE(n, 0).
Show the answer
Football A league table. For each team: matches played and points (3 for a win, 1 for a draw). Ignore postponed matches. Sort by points, highest first, then team name. Columns:
team,played,points.Hint
Turn each match into two rows, one per team, with scored and conceded (UNION ALL). Drop NULL goals. Then points with CASE, and SUM per team.
Show the answer
App For each signup month, the percentage of users who finished onboarding, rounded to 1 place. Count people, not events. Columns:
cohort,pct_onboarded.Hint
Cohort from app_users. DISTINCT user_id from onboarding_done events. LEFT JOIN, then 100.0 * COUNT(matched) / COUNT(*).
Show the answer
Jobs For each company that made an accepted offer: its latest accepted offer's salary and the company's average accepted salary (rounded). Skip missing salaries. Break date ties by the higher offer_id. Columns:
company,latest_salary,avg_salary.Hint
One step for accepted offers with a salary. One step ranks them per company (newest first). One step averages per company. Join the rank-1 rows to the averages and to companies.
Show the answer
Shop Delivered revenue per month with the duplicate order removed, and the change from the month before (rounded to 2 places). Sorted by month. Columns:
month,revenue,change.Hint
Clean step with DISTINCT, monthly step with SUM(quantity * price), then LAG in the final SELECT.
Show the answer
The trap in each question
- Customers with several delivered orders get counted more than once unless you de-dupe them first.
- An inner join drops listeners with no full plays, so the averages go up.
- Postponed matches have NULL goals. Left in, they count as played and NULL = NULL is not a draw.
- One onboarding event is logged twice, so counting events gives one too many.
- A window average over rank-1 rows is the average of one row: the latest salary again.
- The double-submitted order lands in April and inflates April's revenue and both changes around it.
▸ Where next
- Code your teammates can followThe style rules for SQL and Python that make a reviewer trust you.
- SQL by example28 patterns on the same practice data, with a ten-question mock.
- SQL from zeroEvery idea explained slowly, from SELECT up.
- Python by exampleThe same patterns in pandas.
- A take-home, walked throughFrom brief to submitted answer.
- Data tech examsWhat the timed tests look like and how to prepare.