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.

  1. Why stepsNested vs named
  2. The partsWITH, commas, final SELECT
  3. Build and checkOne step at a time
  4. 11 patternsWith Check buttons
  5. RefactorMessy to clean, same result
  6. Test and debugCounts, grain, fan-out
  7. Which tool whenCTE, subquery, temp table, Hex
  8. 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
Result: 2 rows
categoryrevenue
Outdoor1742.0
Kitchen967.0

Steps: read it top to bottom

Show the result without running
Result: 2 rows
categoryrevenue
Outdoor1742.0
Kitchen967.0

Same result both ways: 2 rows, 2 columns.

Same answer. Now look at what the nested one makes you do:

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.

orders raw table one row per order delivered step 1: filter, de-dupe one row per real order category_revenue step 2: join, group one row per category final SELECT keep above average what you get back Each step reads from the steps before it. Each one can be checked on its own. products joins in at step 2
orders raw table, one row per order delivered filter, de-dupe: one row per real order category_revenue join products, group: one per category final SELECT keep above average
The query from section 1 as a pipeline of named tables.

Rules worth knowing

Three errors you will see

You wroteError (SQLite)Fix
A comma after the last step: ... ),
SELECT
near "SELECT": syntax errorDelete the last comma.
WITH a AS (...), WITH b AS (...)near "WITH": syntax errorOne WITH. Commas after that.
A step uses one defined below itno such table: bMove 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
Result: 2 rows
planlistenersavg_plays
premium617.8
free87.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
Result: 1 row
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
Result: 12 rows
listener_idartist_idplays
129
153
112
132
141
223
272
211
251
3213
372
351

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
Result: 9 rows
listener_idartist_idplaysrn
1291
1532
1123
1324
1415
2231
2722
2113
2514

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
Result: 6 rows
listenertop_artistplays
AdaMara Vale9
CaraMara Vale13
FinnMara Vale12
HugoMara Vale5
KaiMara Vale7
NoraThe Gannets3

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
Result: 4 rows
categorynet_revenue
Games158.45
Books153.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
Result: 7 rows
artistfull_plays
Mara Vale66
The Gannets27
Neon Curlew22
Driftwood Kids21
Low Kettle21
Brass Harbour4
Sally Gap4

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
Result: 5 rows
event_nameeventsusers
session_start9333
signup3636
onboarding_done3030
first_post1717
subscribe1010

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

  1. 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
Result: 9 rows
customer_idspend
3674.0
9440.49
13311.5
5280.47
12254.99
10248.0
15222.0
1215.97
16202.0

CTE, then WHERE

Show the result without running
Result: 9 rows
customer_idspend
3674.0
9440.49
13311.5
5280.47
12254.99
10248.0
15222.0
1215.97
16202.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
Result: 13 rows
titlelistenersreach
Glass Tide11wide
Salt Road9wide
Wild Garlic9wide
Wren Song8wide
Ferry Home7steady
Long Grass7steady
Copper Sky6steady
Night Bus6steady
Paper Moon6steady
Blue Hour5steady
Half Light5steady
Iron Bridge5steady
Kite Weather5steady

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
Result: 1 row
namegoals
Harbour United12

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

  1. 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
Result: 7 rows
namesongsplays
Brass Harbour44
Driftwood Kids2121
Low Kettle2222
Mara Vale6767
Neon Curlew2424
Sally Gap44
The Gannets2828

Right: total each list, then join

Show the result without running
Result: 8 rows
namesongsplays
Brass Harbour24
Driftwood Kids321
Low Kettle222
Mara Vale467
Neon Curlew324
Quiet Pylon10
Sally Gap24
The Gannets328

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
Result: 6 rows
namehome_goalsaway_goals
Bogside Athletic3015
Claddagh Town3540
Harbour United6030
Northside Wanderers1015
Riverside Rovers3555
Shannon Celtic2015

Right: total each list, then join

Show the result without running
Result: 6 rows
namehome_goalsaway_goals
Bogside Athletic63
Claddagh Town78
Harbour United126
Northside Wanderers23
Riverside Rovers711
Shannon Celtic43

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

  1. 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
Result: 18 rows
nameorder_idorder_datestatus
Saoirse Doyle692025-06-24delivered
Conor Foley682025-06-17delivered
Oisin Ryan662025-06-14delivered
Roisin Quinn672025-06-14delivered
Eoin Murphy652025-06-13delivered
Ciara Brennan642025-06-11returned
Aisling Keane632025-06-09delivered
Aoife Byrne612025-06-04delivered
Darragh Nolan582025-06-01delivered
Grainne Lynch592025-06-01returned
Niamh Kelly562025-05-14delivered
Fionn Daly552025-05-13delivered
Tadhg Burke532025-05-10delivered
Orla Kavanagh542025-05-10delivered
Cian Walsh502025-04-28cancelled
Sinead Moran432025-04-14returned
Ronan Duffy302025-03-03delivered
Padraig Healy132025-01-28delivered

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
Result: 11 rows
namejob_familyoffered_at
Umberfield SoftwareProduct2024-12-29
Saltmarsh StoresData2024-12-21
Glenvarra EnergyEngineering2024-09-29
Brightwell AnalyticsDesign2024-09-22
Kettlebrook BankEngineering2024-09-08
Harbourlight HealthData2024-08-29
Pixelmoor GamesSales2024-05-07
Larkspur FreightProduct2024-04-08
Copperleaf FoodsEngineering2024-02-09
Willowby InsuranceProduct2023-07-25
Quillstone MediaProduct2023-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
Result: 6 rows
namematch_datescoredconceded
Bogside Athletic2024-09-2803
Claddagh Town2024-09-2121
Harbour United2024-09-2111
Northside Wanderers2024-09-1413
Riverside Rovers2024-09-2812
Shannon Celtic2024-09-2821

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

  1. 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
Result: 6 rows
namecategorypricecategory_avg
Atlas of IslandsBooks38.025.66
Board Game: HarbourGames34.9921.83
Coffee GrinderKitchen75.058.67
Chef KnifeKitchen59.058.67
Rain JacketOutdoor120.084.83
Trail Runner ShoesOutdoor89.084.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
Result: 8 rows
offer_idjob_familybase_salaryvs_family_avg
45Product9200034611.0
26Data8300027273.0
44Data7500019273.0
43Design7400018875.0
5Data7400018273.0
10Product7350016111.0
41Design6850013375.0
37Design6800012875.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
Result: 10 rows
titleartist_idlength_secartist_avg
Salt Road1265223.0
Paper Moon2305225.0
Glass Tide2249225.0
Copper Sky3259206.0
Tin Roof4159156.0
Harbour Lights5207195.0
Blue Hour5207195.0
Static Bloom6218205.0
Last Tram7310262.0
Iron Bridge7300262.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

  1. 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
Result: 1 row
signed_uponboardedpostedsubscribed
36301710

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
Result: 3 rows
platformusersonboardedsubscribedpct_subscribed
ios99444.4
android1614531.3
web11719.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

  1. 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
Result: 6 rows
monthrevenuechangepct_change
2025-01613.99NULLNULL
2025-02320.99-293.0-47.7
2025-03418.4397.4430.4
2025-04991.0572.57136.8
2025-05899.5-91.5-9.2
2025-06490.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
Result: 5 rows
week_fromfull_playschange
2025-03-0112NULL
2025-03-034129
2025-03-10421
2025-03-1741-1
2025-03-2429-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

  1. 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
Result: 4 rows
categoryrevenuepct_of_total
Outdoor1742.046.6
Kitchen967.025.9
Books686.9318.4
Games338.459.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
Result: 5 rows
countrylistenerspct
IE533.3
UK426.7
FR320.0
DE213.3
unknown16.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

  1. 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
Result: 1 row
customer_idproduct_idquantityorder_datecopiesfirst_idlast_id
5522025-04-0824170

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
Result: 1 row
offers_beforeoffers_after
4544

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

  1. 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
Result: 4 rows
cohortcustomerscame_backpct_came_back
2025-019888.9
2025-0233100.0
2025-033266.7
2025-0433100.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
Result: 3 rows
cohortusersactive_next_month
2025-011210
2025-021210
2025-031210

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

  1. 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
Result: 14 rows
artisttitlefull_playsrn
Brass HarbourTin Roof31
Brass HarbourSlow Rain12
Driftwood KidsWren Song111
Driftwood KidsIron Bridge72
Low KettleCopper Sky141
Low KettleNight Bus72
Mara ValeGlass Tide291
Mara ValeFerry Home172
Neon CurlewWild Garlic101
Neon CurlewBlue Hour82
Sally GapHollow Hill31
Sally GapStatic Bloom12
The GannetsSalt Road141
The GannetsKite Weather72

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
Result: 10 rows
job_familyoffer_idbase_salarysalary_rank
Data26830001
Data44750002
Design43740001
Design41685002
Engineering15690001
Engineering30635002
Product45920001
Product10735002
Sales9425001
Sales38420002

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

  1. 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:

  1. Run the original and note the row count and a few values.
  2. Find the innermost subquery. Lift it into the first CTE. Give it a name that says what it holds.
  3. Replace it in the original with the name. Run again. Same result?
  4. Repeat, working outwards, until the final SELECT is short.
  5. 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
Result: 2 rows
planavg_full_plays
free7.6
premium17.3

After

Show the result without running
Result: 2 rows
planavg_full_plays
free7.6
premium17.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
Result: 5 rows
nameaccepted
Saltmarsh Stores7
Copperleaf Foods5
Harbourlight Health5
Larkspur Freight4
Umberfield Software4

After

Show the result without running
Result: 5 rows
nameaccepted
Saltmarsh Stores7
Copperleaf Foods5
Harbourlight Health5
Larkspur Freight4
Umberfield Software4

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
Result: 4 rows
user_idplatform
14ios
15ios
16android
17android

After

Show the result without running
Result: 4 rows
user_idplatform
14ios
15ios
16android
17android

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

  1. 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
Result: 4 rows
stepn_rows
orders70
not_cancelled65
deduped64
with_product64

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
Result: 1 row
n_rowsn_keys
6262

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
Result: 1 row
home_rowsrows_after_join
30150

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
Result: 10 rows
user_idsigned_upsubscribed
711
1211
1411
1611
2511
2811
3011
3111
3311
3611

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

7 CTE, subquery, temp table or Hex cells?

ToolUse it whenWatch out for
CTETwo 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.
SubqueryOne short lookup: WHERE x > (SELECT AVG(x) FROM t) or IN (SELECT id ...).Once it nests two deep, lift it into a CTE.
Temp tableA 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 cellsWorking 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
Result: 1 row
customersavg_spendtop_spend
18207.47674.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 DESC

To 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 DESC

Folding 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
Result: 8 rows
dayplays
2025-03-310
2025-03-300
2025-03-290
2025-03-288
2025-03-274
2025-03-265
2025-03-256
2025-03-247

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
Result: 4 rows
depthname
0Analyst
1Senior Analyst
2Analytics Lead
3Head 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.

0 of 6 correct so far
  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  1. Customers with several delivered orders get counted more than once unless you de-dupe them first.
  2. An inner join drops listeners with no full plays, so the averages go up.
  3. Postponed matches have NULL goals. Left in, they count as played and NULL = NULL is not a draw.
  4. One onboarding event is logged twice, so counting events gives one too many.
  5. A window average over rank-1 rows is the average of one row: the latest salary again.
  6. The double-submitted order lands in April and inflates April's revenue and both changes around it.

▸ Where next