SQL by example
Every common SQL pattern, shown on many kinds of data, then two questions for you to try. Built for students getting ready for data and analytics exams and take-home tasks, often done in Hex.
▸ How to use this page
- Read the pattern. One line and a template you can copy.
- Predict. Before you press Run, guess what comes back. How many rows? Any NULLs?
- Run it, then change it. Every box is editable. Reset puts it back.
- Try it yourself. Write your own query and press Check. It runs yours and a hidden answer and compares the results.
New to SQL? Start with SQL from zero, which explains each idea slowly. This page is the practice book that goes with it.
The queries run in SQLite inside your browser. Hex runs dataframe SQL on DuckDB, which differs in a few places. Look for the Hex and exams boxes, and the table near the end. All the data is made up.
▸ The 28 patterns
Five levels. Most exam questions use levels 1 to 3. The hard ones add 4 and 5.
1Core querying
Pick columns, filter rows, sort.
- 1SELECT, aliases and maths
- 2WHERE with AND, OR, IN, BETWEEN, LIKE
- 3Finding NULLs
- 4ORDER BY and LIMIT: top N
- 5DISTINCT
2Aggregation
Count, add up and group.
- 6COUNT, SUM, AVG, MIN, MAX
- 7GROUP BY
- 8COUNT(DISTINCT)
- 9HAVING against WHERE
- 10ROUND, percentages and the division trap
3Logic and joins
CASE, NULLs, and combining tables.
- 11CASE WHEN: buckets and labels
- 12CASE inside SUM: conditional counts and pivots
- 13COALESCE: fill in the blanks
- 14INNER JOIN
- 15LEFT JOIN and finding what is missing
- 16Joining three tables
- 17Compare to the average: subqueries and self-joins
4Exam structure
CTEs, dates, ranking, de-duping.
- 18CTEs: one step at a time
- 19Dates: by month, by weekday, days between
- 20ROW_NUMBER: latest or first per group
- 21RANK against DENSE_RANK
- 22Top N per group
- 23Finding and removing duplicates
5Analytics
Change, running totals, shares, funnels.
- 24LAG: change against the previous period
- 25Running totals with SUM OVER
- 26Share of total
- 27Funnels and retention
- 28Median and percentiles
▸ The practice data
One small database with five made-up worlds: a shop, a music app, a football league, a phone app and job offers. The traps are real: NULLs, a duplicate row, customers who never ordered, matches not played yet.
See all 14 tables and their columns
Shop
customers
customer_id, name, city, email, signup_date
20 customers. Two never ordered. Some have no city or email.
products
product_id, name, category, price
12 products in 4 categories.
orders
order_id, customer_id, product_id, quantity, order_date, status, discount
Jan to Jun 2025. One order was submitted twice. Most have no discount.
Music
listeners
listener_id, name, country, plan, joined_on
15 listeners. One has never streamed.
artists
artist_id, name, genre
8 artists.
songs
song_id, title, artist_id, length_sec
20 songs. One has never been played.
streams
stream_id, listener_id, song_id, streamed_on, seconds_played
170 plays, 1 to 28 March 2025. Under 30 seconds is a skip.
Football
teams
team_id, name, city
6 teams.
matches
match_id, match_date, home_team_id, away_team_id, home_goals, away_goals
30 fixtures. Four are postponed, with NULL goals.
App
app_users
user_id, signup_date, platform, country, referrer
36 users, 12 a month from Jan to Mar 2025.
events
event_id, user_id, event_name, event_time
signup, onboarding_done, first_post, subscribe, session_start. One row is logged twice.
Jobs
companies
company_id, name, industry, city, size_band
The same 12 companies as SQL from zero.
offers
offer_id, company_id, job_family, level, base_salary, offered_at, accepted_at, status
45 offers. One salary is NULL. Offers 18 and 19 are duplicates.
employees
employee_id, company_id, job_family, level, start_date
30 employees.
L1 Core querying
Pick columns, filter rows, sort.
1SELECT, aliases and mathsLevel 1
Pick the columns you need, rename them with AS, and work out new ones.
SELECT column_a,
column_b AS new_name,
column_c * 2 AS worked_out
FROM table_name;New to this? SQL from zero: SELECT, FROM
Examples
Shop Prices with VAT added
Show the result without running
| name | price | price_with_vat |
|---|---|---|
| Trail Runner Shoes | 89.0 | 109.47 |
| Camping Stove | 45.5 | 55.96 |
| Rain Jacket | 120.0 | 147.6 |
| Board Game: Harbour | 34.99 | 43.04 |
| Puzzle 1000 | 18.0 | 22.14 |
| Card Game: Gulls | 12.5 | 15.38 |
| Chef Knife | 59.0 | 72.57 |
| Cast Iron Pan | 42.0 | 51.66 |
| Coffee Grinder | 75.0 | 92.25 |
| Novel: Low Tide | 14.99 | 18.44 |
| Cookbook: Brown Bread | 24.0 | 29.52 |
| Atlas of Islands | 38.0 | 46.74 |
You can do maths on a column and give the answer a name.
Football Total goals in each match
Predict first: What will total_goals be for a match that has not been played?
Show the result without running
| match_id | match_date | total_goals |
|---|---|---|
| 1 | 2024-08-03 | 2 |
| 2 | 2024-08-03 | 4 |
| 3 | 2024-08-03 | 3 |
| 4 | 2024-08-10 | 1 |
| 5 | 2024-08-10 | 4 |
| 6 | 2024-08-10 | 3 |
| 7 | 2024-08-17 | 3 |
| 8 | 2024-08-17 | 1 |
| 9 | 2024-08-17 | 3 |
| 10 | 2024-08-24 | 2 |
| 11 | 2024-08-24 | 3 |
| 12 | 2024-08-24 | 1 |
| 13 | 2024-08-31 | 3 |
| 14 | 2024-08-31 | 3 |
| 15 | 2024-08-31 | 0 |
| 16 | 2024-09-07 | 7 |
| 17 | 2024-09-07 | 3 |
| 18 | 2024-09-07 | 2 |
| 19 | 2024-09-14 | 5 |
| 20 | 2024-09-14 | 4 |
| 21 | 2024-09-14 | 3 |
| 22 | 2024-09-21 | 1 |
| 23 | 2024-09-21 | 3 |
| 24 | 2024-09-21 | 2 |
| 25 | 2024-09-28 | 3 |
| 26 | 2024-09-28 | 3 |
| 27 | 2024-09-28 | NULL |
| 28 | 2024-10-05 | NULL |
| 29 | 2024-10-05 | NULL |
| 30 | 2024-10-05 | NULL |
Maths with a NULL gives NULL. The four postponed matches have no total.
Music Song length in minutes
Predict first: A song is 215 seconds long. What will minutes_wrong show?
Show the result without running
| title | length_sec | minutes_wrong | minutes |
|---|---|---|---|
| Salt Road | 265 | 4 | 4.4 |
| Kite Weather | 201 | 3 | 3.4 |
| Half Light | 203 | 3 | 3.4 |
| Ferry Home | 192 | 3 | 3.2 |
| Glass Tide | 249 | 4 | 4.2 |
| Paper Moon | 305 | 5 | 5.1 |
| Long Grass | 155 | 2 | 2.6 |
| Copper Sky | 259 | 4 | 4.3 |
| Night Bus | 153 | 2 | 2.5 |
| Slow Rain | 152 | 2 | 2.5 |
| Tin Roof | 159 | 2 | 2.6 |
| Wild Garlic | 172 | 2 | 2.9 |
| Harbour Lights | 207 | 3 | 3.5 |
| Blue Hour | 207 | 3 | 3.5 |
| Hollow Hill | 192 | 3 | 3.2 |
| Static Bloom | 218 | 3 | 3.6 |
| Wren Song | 175 | 2 | 2.9 |
| Last Tram | 310 | 5 | 5.2 |
| Iron Bridge | 300 | 5 | 5.0 |
| Soft Focus | 215 | 3 | 3.6 |
Whole number divided by whole number drops the decimals in SQLite. Add .0 to fix it.
App Glue text together
Show the result without running
| user_id | segment |
|---|---|
| 1 | web / DE |
| 2 | android / IE |
| 3 | web / IE |
| 4 | web / DE |
| 5 | web / UK |
| 6 | web / DE |
| 7 | android / US |
| 8 | android / IE |
| 9 | android / UK |
| 10 | ios / UK |
| 11 | android / IE |
| 12 | android / IE |
| 13 | ios / IE |
| 14 | ios / UK |
| 15 | ios / IE |
| 16 | android / DE |
| 17 | android / IE |
| 18 | web / US |
| 19 | web / DE |
| 20 | web / DE |
| 21 | android / US |
| 22 | web / DE |
| 23 | android / US |
| 24 | ios / UK |
| 25 | ios / US |
| 26 | android / IE |
| 27 | android / IE |
| 28 | ios / IE |
| 29 | ios / IE |
| 30 | web / IE |
| 31 | android / IE |
| 32 | android / UK |
| 33 | android / IE |
| 34 | web / IE |
| 35 | android / IE |
| 36 | ios / IE |
|| joins text. Handy for labels.
Jobs Monthly pay from a yearly salary
Show the result without running
| offer_id | job_family | base_salary | monthly |
|---|---|---|---|
| 1 | Sales | 33000 | 2750.0 |
| 2 | Data | 37000 | 3083.0 |
| 3 | Product | 61000 | 5083.0 |
| 4 | Product | 53500 | 4458.0 |
| 5 | Data | 74000 | 6167.0 |
| 6 | Data | 41500 | 3458.0 |
| 7 | Design | NULL | NULL |
| 8 | Design | 48500 | 4042.0 |
| 9 | Sales | 42500 | 3542.0 |
| 10 | Product | 73500 | 6125.0 |
| 11 | Product | 40000 | 3333.0 |
| 12 | Product | 53500 | 4458.0 |
| 13 | Design | 43500 | 3625.0 |
| 14 | Product | 58500 | 4875.0 |
| 15 | Engineering | 69000 | 5750.0 |
| 16 | Design | 48500 | 4042.0 |
| 17 | Product | 39500 | 3292.0 |
| 18 | Product | 48000 | 4000.0 |
| 19 | Product | 48000 | 4000.0 |
| 20 | Design | 38000 | 3167.0 |
| 21 | Product | 57500 | 4792.0 |
| 22 | Data | 38500 | 3208.0 |
| 23 | Product | 85000 | 7083.0 |
| 24 | Product | 44500 | 3708.0 |
| 25 | Data | 64500 | 5375.0 |
| 26 | Data | 83000 | 6917.0 |
| 27 | Sales | 31500 | 2625.0 |
| 28 | Data | 54500 | 4542.0 |
| 29 | Design | 64000 | 5333.0 |
| 30 | Engineering | 63500 | 5292.0 |
| 31 | Sales | 34000 | 2833.0 |
| 32 | Design | 36500 | 3042.0 |
| 33 | Product | 41000 | 3417.0 |
| 34 | Sales | 29500 | 2458.0 |
| 35 | Data | 43000 | 3583.0 |
| 36 | Data | 57000 | 4750.0 |
| 37 | Design | 68000 | 5667.0 |
| 38 | Sales | 42000 | 3500.0 |
| 39 | Data | 45000 | 3750.0 |
| 40 | Engineering | 52000 | 4333.0 |
| 41 | Design | 68500 | 5708.0 |
| 42 | Engineering | 44000 | 3667.0 |
| 43 | Design | 74000 | 6167.0 |
| 44 | Data | 75000 | 6250.0 |
| 45 | Product | 92000 | 7667.0 |
A NULL salary stays NULL after the maths.
Common mistake
A missing comma does not fail. SELECT name price FROM products shows the names under a heading called price, because SQL reads price as an alias.
Hex and exams: Every SQL cell in Hex returns a dataframe. Rename it from dataframe_1 to something clear like products_vat, because later cells refer to it by that name.
Try it yourself
Music Show each listener's
nameandplan, with the plan column renamedsubscription.Hint
plan AS subscription. This one checks your column names too.Show the answer
Shop Show each product's
nameand its price in cent (price times 100).Hint
Multiply in the SELECT list.
Show the answer
2WHERE with AND, OR, IN, BETWEEN, LIKELevel 1
Keep only the rows that pass a test.
SELECT *
FROM table_name
WHERE column_a = 'some text'
AND column_b BETWEEN 10 AND 20
AND column_c IN ('x', 'y')
AND column_d LIKE 'Start%';New to this? SQL from zero: WHERE
Examples
Shop Delivered orders of two or more items
Show the result without running
| order_id | customer_id | quantity | status |
|---|---|---|---|
| 2 | 15 | 2 | delivered |
| 7 | 17 | 2 | delivered |
| 12 | 13 | 2 | delivered |
| 28 | 3 | 2 | delivered |
| 30 | 18 | 2 | delivered |
| 31 | 5 | 3 | delivered |
| 32 | 11 | 2 | delivered |
| 33 | 13 | 2 | delivered |
| 40 | 12 | 2 | delivered |
| 41 | 5 | 2 | delivered |
| 44 | 9 | 3 | delivered |
| 47 | 10 | 2 | delivered |
| 48 | 16 | 2 | delivered |
| 49 | 3 | 2 | delivered |
| 52 | 5 | 2 | delivered |
| 53 | 12 | 2 | delivered |
| 54 | 13 | 3 | delivered |
| 55 | 10 | 3 | delivered |
| 56 | 3 | 3 | delivered |
| 58 | 6 | 3 | delivered |
| 61 | 1 | 2 | delivered |
| 70 | 5 | 2 | delivered |
AND means both tests must pass.
Jobs Data or Design offers over 50,000
Show the result without running
| offer_id | job_family | base_salary |
|---|---|---|
| 5 | Data | 74000 |
| 25 | Data | 64500 |
| 26 | Data | 83000 |
| 28 | Data | 54500 |
| 29 | Design | 64000 |
| 36 | Data | 57000 |
| 37 | Design | 68000 |
| 41 | Design | 68500 |
| 43 | Design | 74000 |
| 44 | Data | 75000 |
IN is a short way to write several ORs on one column.
Music Songs whose title starts with S
Show the result without running
| title |
|---|
| Salt Road |
| Slow Rain |
| Static Bloom |
| Soft Focus |
% means any run of characters. _ means exactly one.
Football Matches in September 2024
Show the result without running
| match_id | match_date |
|---|---|
| 16 | 2024-09-07 |
| 17 | 2024-09-07 |
| 18 | 2024-09-07 |
| 19 | 2024-09-14 |
| 20 | 2024-09-14 |
| 21 | 2024-09-14 |
| 22 | 2024-09-21 |
| 23 | 2024-09-21 |
| 24 | 2024-09-21 |
| 25 | 2024-09-28 |
| 26 | 2024-09-28 |
| 27 | 2024-09-28 |
BETWEEN includes both ends. Dates stored as YYYY-MM-DD text compare correctly.
App OR needs brackets
Predict first: Take the brackets away and run it again. Do you get more rows or fewer?
Show the result without running
| user_id | platform | country |
|---|---|---|
| 2 | android | IE |
| 8 | android | IE |
| 11 | android | IE |
| 12 | android | IE |
| 13 | ios | IE |
| 15 | ios | IE |
| 17 | android | IE |
| 26 | android | IE |
| 27 | android | IE |
| 28 | ios | IE |
| 29 | ios | IE |
| 31 | android | IE |
| 33 | android | IE |
| 35 | android | IE |
| 36 | ios | IE |
The brackets make the OR happen first.
Common mistake
AND is worked out before OR. WHERE platform = 'ios' OR platform = 'android' AND country = 'IE' returns every iOS user from every country. Put brackets round the OR.
Hex and exams: In Hex, dataframe SQL runs on DuckDB. There, LIKE cares about capital letters and ILIKE does not. In SQLite, LIKE ignores case for plain letters. Text always goes in single quotes: DuckDB reads "Dublin" as a column name.
Try it yourself
Jobs List
offer_idandbase_salaryfor Junior offers paying from 35,000 to 40,000, both ends included.Hint
level = 'Junior'and BETWEEN.Show the answer
Shop Find customers in Cork or Galway who signed up before 1 November 2024. Return
nameandcity.Hint
IN for the cities, then compare
signup_dateto'2024-11-01'.Show the answer
3Finding NULLsLevel 1
NULL means unknown. Test for it with IS NULL, never = NULL.
SELECT * FROM table_name WHERE column_a IS NULL -- missing OR column_b IS NOT NULL; -- present
New to this? SQL from zero: NULL
Examples
Shop Customers with no email
Show the result without running
| customer_id | name |
|---|---|
| 6 | Darragh Nolan |
| 14 | Padraig Healy |
The simplest NULL check.
Football Matches not played yet
Show the result without running
| match_id | match_date |
|---|---|
| 27 | 2024-09-28 |
| 28 | 2024-10-05 |
| 29 | 2024-10-05 |
| 30 | 2024-10-05 |
No score yet means NULL, not 0.
Jobs = NULL finds nothing
Predict first: Some offers were never accepted. How many rows will this return?
Show the result without running
| offer_id |
|---|
Comparing anything to NULL gives unknown, so no row passes.
Music COUNT(*) against COUNT(column)
Show the result without running
| listeners | with_country |
|---|---|
| 15 | 14 |
COUNT(column) skips NULLs. COUNT(*) counts every row.
App Not equal also drops NULLs
Predict first: Will users with a NULL referrer appear?
Show the result without running
| user_id | referrer |
|---|---|
| 2 | search |
| 5 | friend |
| 6 | search |
| 10 | search |
| 15 | search |
| 16 | search |
| 17 | friend |
| 18 | search |
| 22 | search |
| 23 | search |
| 25 | friend |
| 26 | friend |
| 27 | friend |
| 31 | friend |
| 32 | friend |
| 36 | search |
Users with no referrer are missing from the result, though they did not come from an ad.
Common mistake
WHERE referrer <> 'ad' quietly drops every NULL row. If you want them, say so: WHERE referrer <> 'ad' OR referrer IS NULL.
Hex and exams: A blank cell in a Hex result table is usually NULL. Check with IS NULL before you treat it as an empty string.
Try it yourself
Jobs Which companies have no city recorded? Return
name.Hint
The table is
companies.Show the answer
App List the
user_idof every user whose referrer is not 'friend'. Include users with no referrer.Hint
Two conditions joined by OR.
Show the answer
4ORDER BY and LIMIT: top NLevel 1
Sort the rows, then keep the first few.
SELECT column_a, column_b FROM table_name ORDER BY column_b DESC -- biggest first LIMIT 5;
New to this? SQL from zero: ORDER BY, LIMIT
Examples
Shop Three dearest products
Show the result without running
| name | price |
|---|---|
| Rain Jacket | 120.0 |
| Trail Runner Shoes | 89.0 |
| Coffee Grinder | 75.0 |
DESC sorts biggest first. ASC (the default) sorts smallest first.
Music Five longest songs
Show the result without running
| title | length_sec |
|---|---|
| Last Tram | 310 |
| Paper Moon | 305 |
| Iron Bridge | 300 |
| Salt Road | 265 |
| Copper Sky | 259 |
Top N is ORDER BY plus LIMIT.
Jobs Sort by two columns
Show the result without running
| offer_id | job_family | base_salary |
|---|---|---|
| 26 | Data | 83000 |
| 44 | Data | 75000 |
| 5 | Data | 74000 |
| 25 | Data | 64500 |
| 36 | Data | 57000 |
| 28 | Data | 54500 |
| 39 | Data | 45000 |
| 35 | Data | 43000 |
| 6 | Data | 41500 |
| 22 | Data | 38500 |
| 2 | Data | 37000 |
| 43 | Design | 74000 |
| 41 | Design | 68500 |
| 37 | Design | 68000 |
| 29 | Design | 64000 |
| 8 | Design | 48500 |
| 16 | Design | 48500 |
| 13 | Design | 43500 |
| 20 | Design | 38000 |
| 32 | Design | 36500 |
| 7 | Design | NULL |
| 15 | Engineering | 69000 |
| 30 | Engineering | 63500 |
| 40 | Engineering | 52000 |
| 42 | Engineering | 44000 |
| 45 | Product | 92000 |
| 23 | Product | 85000 |
| 10 | Product | 73500 |
| 3 | Product | 61000 |
| 14 | Product | 58500 |
| 21 | Product | 57500 |
| 4 | Product | 53500 |
| 12 | Product | 53500 |
| 18 | Product | 48000 |
| 19 | Product | 48000 |
| 24 | Product | 44500 |
| 33 | Product | 41000 |
| 11 | Product | 40000 |
| 17 | Product | 39500 |
| 9 | Sales | 42500 |
| 38 | Sales | 42000 |
| 31 | Sales | 34000 |
| 1 | Sales | 33000 |
| 27 | Sales | 31500 |
| 34 | Sales | 29500 |
The second column breaks ties inside the first.
Football Where do NULLs go?
Predict first: Which matches will be at the top: 0-0 draws or the postponed ones?
Show the result without running
| match_id | goals |
|---|---|
| 27 | NULL |
| 28 | NULL |
| 29 | NULL |
| 30 | NULL |
| 15 | 0 |
| 4 | 1 |
SQLite puts NULLs first when sorting smallest first.
App Newest sign-ups
Show the result without running
| user_id | signup_date |
|---|---|
| 32 | 2025-03-26 |
| 33 | 2025-03-26 |
| 27 | 2025-03-25 |
| 26 | 2025-03-24 |
| 28 | 2025-03-24 |
ISO dates sort correctly as text.
Common mistake
LIMIT without ORDER BY gives you any N rows, not the top N. And check for ties at the cut-off: if rows 3 and 4 have the same value, LIMIT 3 picks one for you.
Hex and exams: DuckDB (Hex) puts NULLs last when sorting smallest first. SQLite puts them first. If it matters, write ORDER BY goals NULLS LAST. Both accept it.
Try it yourself
Jobs Show the three most recent hires in
employees:employee_idandstart_date, newest first.Hint
ORDER BY start_date DESC, then LIMIT.
Show the answer
Shop The four cheapest products:
nameandprice, cheapest first.Hint
ASC is the default.
Show the answer
5DISTINCTLevel 1
Show each different value once.
SELECT DISTINCT column_a FROM table_name;
New to this? SQL from zero: DISTINCT
Examples
Shop Cities our customers live in
Predict first: Will a blank city appear in the list?
Show the result without running
| city |
|---|
| NULL |
| Cork |
| Dublin |
| Galway |
| Limerick |
| Waterford |
NULL counts as one value and shows once.
Jobs Distinct pairs
Show the result without running
| job_family | level |
|---|---|
| Data | Junior |
| Data | Mid |
| Data | Senior |
| Design | Junior |
| Design | Mid |
| Design | Senior |
| Engineering | Junior |
| Engineering | Mid |
| Product | Junior |
| Product | Mid |
| Product | Senior |
| Sales | Junior |
| Sales | Mid |
DISTINCT works on the whole row: each family and level pair once.
Music Who streamed anything?
Show the result without running
| listener_id |
|---|
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 11 |
| 12 |
| 13 |
| 14 |
| 15 |
One row per listener, however many times they played.
App Every event type
Show the result without running
| event_name |
|---|
| signup |
| onboarding_done |
| session_start |
| first_post |
| subscribe |
A quick way to see what values a column holds.
Common mistake
DISTINCT applies to every column you select. SELECT DISTINCT city, name gives one row per customer, not one per city.
Hex and exams: "How many different X?" is COUNT(DISTINCT x), not DISTINCT on its own. See pattern 8.
Try it yourself
Shop Which
product_ids have ever been ordered? One row each.Hint
DISTINCT on the orders table.
Show the answer
App List each different
countryinapp_users.Hint
One column, DISTINCT.
Show the answer
L2 Aggregation
Count, add up and group.
6COUNT, SUM, AVG, MIN, MAXLevel 2
Squash many rows into one number.
SELECT COUNT(*) AS rows_,
SUM(column_a) AS total,
AVG(column_a) AS average,
MIN(column_a) AS smallest,
MAX(column_a) AS biggest
FROM table_name;New to this? SQL from zero: COUNT, SUM, AVG
Examples
Shop Orders at a glance
Show the result without running
| orders | units | first_order | last_order |
|---|---|---|---|
| 70 | 100 | 2025-01-03 | 2025-06-24 |
MIN and MAX work on dates and text too.
Jobs AVG skips NULLs
Predict first: Why might with_salary be smaller than offers?
Show the result without running
| offers | with_salary | avg_salary |
|---|---|---|
| 45 | 44 | 53159.0 |
One offer has no salary. AVG divides by 44, not 45.
Music Hours of music played
Show the result without running
| hours |
|---|
| 9.0 |
Divide by 3600.0, not 3600, to keep the decimals.
Football Goals per match
Show the result without running
| home | away | avg_goals |
|---|---|---|
| 38 | 34 | 2.77 |
Postponed matches are NULL, so SUM and AVG ignore them.
Common mistake
SELECT city, COUNT(*) FROM customers runs in SQLite and returns one row with a random city. DuckDB and most databases refuse it. A plain column next to an aggregate needs GROUP BY.
Hex and exams: DuckDB in Hex will error on that mixed query. Good: an error is better than a wrong number.
Try it yourself
Shop What are the cheapest and dearest product prices? Return two columns:
min_price,max_price.Hint
MIN and MAX on
price.Show the answer
Music What is the average song length in seconds, rounded to 1 decimal?
Hint
ROUND(AVG(...), 1)on thesongstable.Show the answer
7GROUP BYLevel 2
One row per group, with an aggregate for each.
SELECT group_column,
COUNT(*) AS rows_,
SUM(value_column) AS total
FROM table_name
GROUP BY group_column;New to this? SQL from zero: GROUP BY
Examples
Shop Orders by status
Show the result without running
| status | orders |
|---|---|
| cancelled | 5 |
| delivered | 57 |
| returned | 8 |
Each different status becomes one row.
Music Most-played songs
Show the result without running
| song_id | plays |
|---|---|
| 5 | 29 |
| 4 | 18 |
| 8 | 14 |
| 1 | 14 |
| 6 | 12 |
GROUP BY, then ORDER BY the count, then LIMIT.
Jobs Two grouping columns
Show the result without running
| job_family | level | offers | avg_salary |
|---|---|---|---|
| Data | Junior | 5 | 41000.0 |
| Data | Mid | 2 | 55750.0 |
| Data | Senior | 4 | 74125.0 |
| Design | Junior | 3 | 37250.0 |
| Design | Mid | 3 | 46833.0 |
| Design | Senior | 4 | 68625.0 |
| Engineering | Junior | 2 | 48000.0 |
| Engineering | Mid | 2 | 66250.0 |
| Product | Junior | 6 | 43500.0 |
| Product | Mid | 5 | 56800.0 |
| Product | Senior | 3 | 83500.0 |
| Sales | Junior | 4 | 32000.0 |
| Sales | Mid | 2 | 42250.0 |
One row for each family and level pair.
App Users per platform
Show the result without running
| platform | users |
|---|---|
| android | 16 |
| ios | 9 |
| web | 11 |
The classic "how many in each" question.
Football Home goals by team
Show the result without running
| home_team_id | home_goals |
|---|---|
| 2 | 12 |
| 4 | 7 |
| 1 | 7 |
| 3 | 6 |
| 5 | 4 |
| 6 | 2 |
You can sort by the alias of an aggregate.
Common mistake
Every column in SELECT must be in GROUP BY or inside an aggregate. Otherwise SQLite picks a value for you and most other databases error.
Hex and exams: DuckDB has GROUP BY ALL, which groups by every column that is not an aggregate. Handy in Hex. SQLite does not have it, and exam graders often expect the full list.
Try it yourself
Shop How many customers live in each city? Return
cityandcustomers. Keep customers with no city as their own group.Hint
GROUP BY city. Do not filter out the NULL.
Show the answer
Jobs How many employees does each company have? Return
company_idandemployees.Hint
Group the
employeestable bycompany_id.Show the answer
8COUNT(DISTINCT)Level 2
Count how many different things, not how many rows.
SELECT COUNT(*) AS rows_,
COUNT(DISTINCT person_id) AS people
FROM table_name;New to this? SQL from zero: DISTINCT
Examples
Music Streams, listeners and songs
Predict first: Will listeners be 15, the size of the listeners table?
Show the result without running
| streams | listeners | songs |
|---|---|---|
| 170 | 14 | 19 |
170 rows, but far fewer people and songs.
Shop Orders and buyers per month
Show the result without running
| month | orders | buyers |
|---|---|---|
| 2025-01 | 15 | 9 |
| 2025-02 | 12 | 8 |
| 2025-03 | 9 | 9 |
| 2025-04 | 15 | 11 |
| 2025-05 | 7 | 6 |
| 2025-06 | 12 | 10 |
Orders count rows. Buyers count people. (Dates are pattern 19.)
App Events against users
Show the result without running
| event_name | events | users |
|---|---|---|
| first_post | 17 | 17 |
| onboarding_done | 31 | 30 |
| session_start | 93 | 33 |
| signup | 36 | 36 |
| subscribe | 10 | 10 |
Sessions: many events from fewer users.
Jobs Companies hiring in each family
Show the result without running
| job_family | offers | companies |
|---|---|---|
| Data | 11 | 6 |
| Design | 10 | 6 |
| Engineering | 4 | 4 |
| Product | 14 | 7 |
| Sales | 6 | 4 |
Fourteen Product offers come from just seven companies.
Common mistake
"How many users" almost always means COUNT(DISTINCT user_id). COUNT(*) counts a user with five sessions five times.
Try it yourself
Shop How many different customers have placed at least one order? One number.
Hint
COUNT(DISTINCT ...) on orders.
Show the answer
Music For each
song_id, how many different listeners played it? Returnsong_idandlisteners.Hint
GROUP BY song_id with COUNT(DISTINCT listener_id).
Show the answer
9HAVING against WHERELevel 2
WHERE filters rows before grouping. HAVING filters groups after.
SELECT group_column, COUNT(*) AS n FROM table_name WHERE row_condition -- before grouping GROUP BY group_column HAVING COUNT(*) >= 5; -- after grouping
New to this? SQL from zero: HAVING
Examples
Shop Customers with five or more orders
Show the result without running
| customer_id | orders |
|---|---|
| 1 | 8 |
| 2 | 6 |
| 3 | 7 |
| 5 | 6 |
| 7 | 6 |
| 10 | 5 |
The test is on the count, so it must be HAVING.
Jobs Both in one query
Show the result without running
| job_family | accepted | avg_salary |
|---|---|---|
| Data | 11 | 55727.0 |
| Design | 9 | 55125.0 |
| Engineering | 4 | 57125.0 |
| Product | 9 | 57389.0 |
WHERE keeps accepted offers. HAVING keeps families with a high average.
Music Songs played by four or more people
Show the result without running
| song_id | listeners |
|---|---|
| 1 | 9 |
| 2 | 5 |
| 3 | 5 |
| 4 | 7 |
| 5 | 11 |
| 6 | 6 |
| 7 | 7 |
| 8 | 6 |
| 9 | 6 |
| 12 | 9 |
| 14 | 5 |
| 17 | 8 |
| 19 | 5 |
HAVING can use any aggregate.
App Heavy users
Predict first: Move the event_name test into HAVING. Does it still run?
Show the result without running
| user_id | sessions |
|---|---|
| 21 | 8 |
| 2 | 7 |
Filter to sessions first, then keep users with more than five.
Common mistake
WHERE COUNT(*) > 5 is an error. When WHERE runs, the groups do not exist yet. SQL works in this order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.
Hex and exams: SQLite and DuckDB let you use a SELECT alias in HAVING (HAVING sessions > 5). Some warehouses do not. In an exam, repeat the expression to be safe.
Try it yourself
Jobs Which companies made more than four offers? Return
company_idandoffers.Hint
GROUP BY company_id, HAVING COUNT(*) > 4.
Show the answer
Football Which home teams scored 7 or more goals at home? Return
home_team_idandgoals.Hint
SUM(home_goals) in HAVING.
Show the answer
10ROUND, percentages and the division trapLevel 2
Multiply by 100.0 first, then divide, then round.
SELECT ROUND(100.0 * part / total, 1) AS pct FROM ...;
New to this? SQL from zero: COUNT, SUM, AVG
Examples
Shop The trap on its own
Predict first: What will whole_numbers show?
Show the result without running
| whole_numbers | with_decimal | pct |
|---|---|---|
| 0 | 0.07142857142857142 | 7.1 |
Two whole numbers give a whole-number answer in SQLite. 5 / 70 is 0.
Football Goals per match, right and wrong
Show the result without running
| goals | played | per_match_wrong | per_match |
|---|---|---|---|
| 72 | 26 | 2 | 2.77 |
1.0 * turns the sum into a decimal before dividing.
Jobs Acceptance rate by family
Show the result without running
| job_family | offers | pct_accepted |
|---|---|---|
| Data | 11 | 100.0 |
| Design | 10 | 90.0 |
| Engineering | 4 | 100.0 |
| Product | 14 | 64.3 |
| Sales | 6 | 83.3 |
COUNT(column) counts non-NULLs: here, offers with an accepted date.
App Share of users who subscribed
Show the result without running
| pct_subscribed |
|---|
| 27.8 |
Two small queries in brackets, one divided by the other.
Common mistake
COUNT(x) / COUNT(*) * 100 gives 0 in SQLite, Postgres and SQL Server, because the division happens first. Put 100.0 * at the front.
Hex and exams: In DuckDB (Hex), / always gives a decimal: 5 / 70 is 0.071. Use // for whole-number division. So a query can be right in Hex and wrong in SQLite. Writing 100.0 * is right everywhere.
Try it yourself
Music What percentage of listeners have a country recorded? One number, rounded to 1 decimal.
Hint
COUNT(country) over COUNT(*). Watch the division.
Show the answer
Jobs For each
level, the percentage of offers that have anaccepted_atdate, rounded to 1 decimal. Returnlevelandpct.Hint
Same shape as the acceptance-rate example, grouped by level.
Show the answer
L3 Logic and joins
CASE, NULLs, and combining tables.
11CASE WHEN: buckets and labelsLevel 3
Turn values into labels. The first WHEN that is true wins.
SELECT column_a,
CASE WHEN column_a < 20 THEN 'low'
WHEN column_a < 60 THEN 'mid'
ELSE 'high'
END AS band
FROM table_name;New to this? SQL from zero: CASE WHEN
Examples
Shop Price bands
Show the result without running
| name | price | band |
|---|---|---|
| Card Game: Gulls | 12.5 | budget |
| Novel: Low Tide | 14.99 | budget |
| Puzzle 1000 | 18.0 | budget |
| Cookbook: Brown Bread | 24.0 | mid |
| Board Game: Harbour | 34.99 | mid |
| Atlas of Islands | 38.0 | mid |
| Cast Iron Pan | 42.0 | mid |
| Camping Stove | 45.5 | mid |
| Chef Knife | 59.0 | mid |
| Coffee Grinder | 75.0 | premium |
| Trail Runner Shoes | 89.0 | premium |
| Rain Jacket | 120.0 | premium |
The 45.50 camping stove fails the first test and passes the second.
Football Match results
Predict first: What label will the postponed matches get?
Show the result without running
| match_id | home_goals | away_goals | result |
|---|---|---|---|
| 1 | 0 | 2 | away win |
| 2 | 2 | 2 | draw |
| 3 | 3 | 0 | home win |
| 4 | 1 | 0 | home win |
| 5 | 2 | 2 | draw |
| 6 | 1 | 2 | away win |
| 7 | 1 | 2 | away win |
| 8 | 0 | 1 | away win |
| 9 | 0 | 3 | away win |
| 10 | 2 | 0 | home win |
| 11 | 2 | 1 | home win |
| 12 | 1 | 0 | home win |
| 13 | 2 | 1 | home win |
| 14 | 2 | 1 | home win |
| 15 | 0 | 0 | draw |
| 16 | 2 | 5 | away win |
| 17 | 3 | 0 | home win |
| 18 | 1 | 1 | draw |
| 19 | 3 | 2 | home win |
| 20 | 3 | 1 | home win |
| 21 | 2 | 1 | home win |
| 22 | 0 | 1 | away win |
| 23 | 2 | 1 | home win |
| 24 | 1 | 1 | draw |
| 25 | 0 | 3 | away win |
| 26 | 2 | 1 | home win |
| 27 | NULL | NULL | not played |
| 28 | NULL | NULL | not played |
| 29 | NULL | NULL | not played |
| 30 | NULL | NULL | not played |
NULL fails every comparison, so postponed games fall through to ELSE.
Music Skips against listens
Show the result without running
| kind | streams |
|---|---|
| listen | 165 |
| skip | 5 |
Bucket first, then GROUP BY the bucket.
Jobs Salary bands with a NULL
Predict first: How many bands will you see?
Show the result without running
| band | offers |
|---|---|
| NULL | 1 |
| 45k-60k | 12 |
| 60k+ | 14 |
| under 45k | 18 |
No ELSE means NULL. The missing salary gets its own NULL band.
Common mistake
Order matters. WHEN price < 60 THEN 'mid' WHEN price < 20 THEN 'budget' never says budget, because anything under 20 is also under 60 and stops at the first line.
Hex and exams: CASE is the same in SQLite, DuckDB and every warehouse. Safe to use anywhere.
Try it yourself
App Label each user
'mobile'if platform is ios or android, otherwise'desktop'. Returnuser_idanddevice.Hint
WHEN platform IN ('ios', 'android').Show the answer
Shop Label customers
'early'if they signed up before 1 November 2024, otherwise'late'. Count each label. Returnlabelandcustomers.Hint
Strictly before means
<, not<=.Show the answer
12CASE inside SUM: conditional counts and pivotsLevel 3
Count only the rows that match, side by side in one row.
SELECT group_column,
SUM(CASE WHEN condition_a THEN 1 ELSE 0 END) AS n_a,
SUM(CASE WHEN condition_b THEN 1 ELSE 0 END) AS n_b
FROM table_name
GROUP BY group_column;New to this? SQL from zero: CASE WHEN
Examples
Shop Delivered against not delivered
Show the result without running
| customer_id | orders | delivered | not_delivered |
|---|---|---|---|
| 1 | 8 | 6 | 2 |
| 2 | 6 | 4 | 2 |
| 3 | 7 | 7 | 0 |
| 4 | 3 | 2 | 1 |
| 5 | 6 | 6 | 0 |
| 6 | 2 | 2 | 0 |
| 7 | 6 | 3 | 3 |
| 8 | 4 | 3 | 1 |
| 9 | 3 | 3 | 0 |
| 10 | 5 | 4 | 1 |
| 11 | 2 | 1 | 1 |
| 12 | 4 | 4 | 0 |
| 13 | 3 | 3 | 0 |
| 14 | 1 | 1 | 0 |
| 15 | 4 | 3 | 1 |
| 16 | 2 | 2 | 0 |
| 17 | 3 | 2 | 1 |
| 18 | 1 | 1 | 0 |
Each CASE gives 1 or 0. SUM adds up the 1s.
Football Home record per team
Show the result without running
| home_team_id | won | drawn | lost |
|---|---|---|---|
| 1 | 2 | 2 | 0 |
| 2 | 3 | 1 | 1 |
| 3 | 2 | 0 | 2 |
| 4 | 3 | 1 | 1 |
| 5 | 2 | 1 | 2 |
| 6 | 1 | 0 | 2 |
Postponed games count in none of the three.
App A yes/no flag per user
Show the result without running
| user_id | sessions | subscribed |
|---|---|---|
| 1 | 3 | 0 |
| 2 | 7 | 0 |
| 3 | 1 | 0 |
| 4 | 2 | 0 |
| 5 | 5 | 0 |
| 6 | 4 | 0 |
| 7 | 2 | 1 |
| 8 | 3 | 0 |
| 9 | 4 | 0 |
| 10 | 5 | 0 |
| 11 | 1 | 0 |
| 12 | 4 | 1 |
| 13 | 1 | 0 |
| 14 | 2 | 1 |
| 15 | 2 | 0 |
| 16 | 2 | 1 |
| 17 | 2 | 0 |
| 18 | 3 | 0 |
| 19 | 0 | 0 |
| 20 | 3 | 0 |
| 21 | 8 | 0 |
| 22 | 3 | 0 |
| 23 | 5 | 0 |
| 24 | 0 | 0 |
| 25 | 1 | 1 |
| 26 | 2 | 0 |
| 27 | 1 | 0 |
| 28 | 1 | 1 |
| 29 | 1 | 0 |
| 30 | 4 | 1 |
| 31 | 3 | 1 |
| 32 | 1 | 0 |
| 33 | 1 | 1 |
| 34 | 3 | 0 |
| 35 | 0 | 0 |
| 36 | 3 | 1 |
MAX of a 1/0 CASE asks "did it ever happen?"
Jobs Pivot: levels across the top
Show the result without running
| job_family | junior | mid | senior |
|---|---|---|---|
| Data | 5 | 2 | 4 |
| Design | 3 | 3 | 4 |
| Engineering | 2 | 2 | 0 |
| Product | 6 | 5 | 3 |
| Sales | 4 | 2 | 0 |
Rows become columns. This is a pivot by hand.
Music Skip rate per listener
Show the result without running
| listener_id | streams | skip_pct |
|---|---|---|
| 2 | 8 | 12.5 |
| 7 | 10 | 10.0 |
| 8 | 14 | 7.1 |
| 14 | 15 | 6.7 |
| 3 | 17 | 5.9 |
| 15 | 4 | 0.0 |
| 13 | 3 | 0.0 |
| 12 | 16 | 0.0 |
| 11 | 17 | 0.0 |
| 9 | 4 | 0.0 |
| 6 | 27 | 0.0 |
| 5 | 12 | 0.0 |
| 4 | 6 | 0.0 |
| 1 | 17 | 0.0 |
Conditional count over total count gives a rate.
Common mistake
COUNT(CASE WHEN ... THEN 1 ELSE 0 END) counts every row, because 0 is not NULL. Use SUM with ELSE 0, or COUNT with no ELSE.
Hex and exams: DuckDB (and SQLite) also accept COUNT(*) FILTER (WHERE status = 'delivered'), and DuckDB has a PIVOT command. CASE works in every database, so use it in exams.
Try it yourself
Shop For each
product_id, count delivered orders and returned orders. Returnproduct_id,delivered,returned.Hint
Two SUM(CASE ...) columns, GROUP BY product_id.
Show the answer
Music For each
countryin listeners, count premium and free listeners. Returncountry,premium,free.Hint
GROUP BY country, one SUM(CASE ...) per plan.
Show the answer
13COALESCE: fill in the blanksLevel 3
Use the first value that is not NULL.
SELECT COALESCE(column_a, 'fallback') AS column_a FROM table_name;
New to this? SQL from zero: NULL
Examples
Shop Missing discount as 0
Show the result without running
| order_id | discount | discount_filled |
|---|---|---|
| 1 | NULL | 0 |
| 2 | NULL | 0 |
| 3 | NULL | 0 |
| 4 | NULL | 0 |
| 5 | NULL | 0 |
| 6 | NULL | 0 |
| 7 | NULL | 0 |
| 8 | NULL | 0 |
NULL becomes 0. Real values stay as they are.
Jobs A label for unknown cities
Show the result without running
| name | city |
|---|---|
| Brightwell Analytics | Dublin |
| Copperleaf Foods | Cork |
| Harbourlight Health | Galway |
| Kettlebrook Bank | Dublin |
| Pixelmoor Games | Dublin |
| Quillstone Media | London |
| Glenvarra Energy | Cork |
| Saltmarsh Stores | Limerick |
| Larkspur Freight | Unknown |
| Umberfield Software | London |
| Willowby Insurance | Galway |
| Zillmere Robotics | Berlin |
Good for display and for grouping.
Music Group the unknowns with a name
Show the result without running
| country | listeners |
|---|---|
| DE | 2 |
| FR | 3 |
| IE | 5 |
| UK | 4 |
| unknown | 1 |
GROUP BY 1 means group by the first column in SELECT.
Shop Filling changes the average
Predict first: Which number will be bigger?
Show the result without running
| avg_when_given | avg_per_order |
|---|---|
| 6.67 | 1.14 |
Two different questions with two different answers.
App Missing referrer means direct
Show the result without running
| source | users |
|---|---|
| ad | 13 |
| direct | 7 |
| friend | 7 |
| search | 9 |
Only do this when NULL really means something.
Common mistake
Filling NULL with 0 changes the meaning. A postponed match is not a 0-0 draw. Ask what the blank means before you fill it.
Hex and exams: In pandas the same idea is fillna(). SQLite also has IFNULL(a, b) and Snowflake has NVL(a, b). COALESCE works everywhere and takes any number of values.
Try it yourself
Shop Show each customer's
nameandemail. Where the email is missing, show'no email'.Hint
COALESCE(email, 'no email').
Show the answer
Shop Average discount per order, counting orders with no discount as 0. Round to 2 decimals.
Hint
AVG of a COALESCE.
Show the answer
14INNER JOINLevel 3
Put two tables side by side where a key matches. Rows with no match drop out.
SELECT a.column_x, b.column_y FROM table_a AS a JOIN table_b AS b ON b.key = a.key;
New to this? SQL from zero: JOINs
Examples
Shop Orders with product names
Show the result without running
| order_id | order_date | name | quantity | line_total |
|---|---|---|---|---|
| 1 | 2025-01-03 | Trail Runner Shoes | 1 | 89.0 |
| 2 | 2025-01-09 | Camping Stove | 2 | 91.0 |
| 3 | 2025-01-13 | Puzzle 1000 | 1 | 18.0 |
| 4 | 2025-01-14 | Cookbook: Brown Bread | 1 | 24.0 |
| 5 | 2025-01-18 | Atlas of Islands | 1 | 38.0 |
| 6 | 2025-01-19 | Board Game: Harbour | 1 | 34.99 |
| 7 | 2025-01-21 | Cookbook: Brown Bread | 2 | 48.0 |
| 8 | 2025-01-25 | Cast Iron Pan | 1 | 42.0 |
| 9 | 2025-01-25 | Atlas of Islands | 1 | 38.0 |
| 10 | 2025-01-26 | Board Game: Harbour | 1 | 34.99 |
Short aliases (o, p) keep it readable.
Music Songs with their artist
Show the result without running
| title | artist | genre |
|---|---|---|
| Salt Road | The Gannets | Indie |
| Kite Weather | The Gannets | Indie |
| Half Light | The Gannets | Indie |
| Ferry Home | Mara Vale | Pop |
| Glass Tide | Mara Vale | Pop |
| Paper Moon | Mara Vale | Pop |
| Long Grass | Mara Vale | Pop |
| Copper Sky | Low Kettle | Folk |
| Night Bus | Low Kettle | Folk |
| Slow Rain | Brass Harbour | Jazz |
| Tin Roof | Brass Harbour | Jazz |
| Wild Garlic | Neon Curlew | Electronic |
| Harbour Lights | Neon Curlew | Electronic |
| Blue Hour | Neon Curlew | Electronic |
| Hollow Hill | Sally Gap | Folk |
| Static Bloom | Sally Gap | Folk |
| Wren Song | Driftwood Kids | Indie |
| Last Tram | Driftwood Kids | Indie |
| Iron Bridge | Driftwood Kids | Indie |
| Soft Focus | Quiet Pylon | Ambient |
Many songs to one artist.
Jobs Tech offers with company names
Show the result without running
| name | job_family | base_salary |
|---|---|---|
| Umberfield Software | Product | 61000 |
| Pixelmoor Games | Product | 53500 |
| Umberfield Software | Engineering | 69000 |
| Brightwell Analytics | Design | 38000 |
| Pixelmoor Games | Data | 64500 |
| Brightwell Analytics | Design | 36500 |
| Pixelmoor Games | Sales | 29500 |
| Umberfield Software | Design | 68000 |
| Brightwell Analytics | Design | 68500 |
| Umberfield Software | Design | 74000 |
| Umberfield Software | Product | 92000 |
Join first, then filter on either table.
Football Home team names
Show the result without running
| match_date | home_team | home_goals | away_goals |
|---|---|---|---|
| 2024-08-03 | Shannon Celtic | 0 | 2 |
| 2024-08-03 | Riverside Rovers | 2 | 2 |
| 2024-08-03 | Harbour United | 3 | 0 |
| 2024-08-10 | Shannon Celtic | 1 | 0 |
| 2024-08-10 | Harbour United | 2 | 2 |
| 2024-08-10 | Harbour United | 1 | 2 |
| 2024-08-17 | Northside Wanderers | 1 | 2 |
| 2024-08-17 | Northside Wanderers | 0 | 1 |
The key can have a different name on each side.
Shop Revenue by category
Show the result without running
| category | revenue |
|---|---|
| Outdoor | 1742.0 |
| Kitchen | 967.0 |
| Books | 686.93 |
| Games | 338.45 |
Join, filter, group: the shape of most exam questions.
Common mistake
A join on the wrong key still runs. ON p.product_id = o.order_id returns rows that look fine and mean nothing. Check the row count before and after every join.
Hex and exams: If a join makes more rows than you expected, the key is not unique on one side. Exams often hide a duplicate to test this. Count rows in a quick cell before moving on.
Try it yourself
Jobs For each employee at a Dublin company, show
employee_idand the companyname.Hint
Join employees to companies, then WHERE c.city = 'Dublin'.
Show the answer
Music Count streams by listener plan. Return
planandstreams.Hint
Join streams to listeners, GROUP BY plan.
Show the answer
15LEFT JOIN and finding what is missingLevel 3
Keep every row from the left table, matched or not. Then look for the NULLs.
SELECT a.* FROM table_a a LEFT JOIN table_b b ON b.key = a.key WHERE b.key IS NULL; -- in a, not in b
New to this? SQL from zero: JOINs
Examples
Shop Orders per customer, including none
Predict first: Who will be at the top of the list?
Show the result without running
| customer_id | name | orders |
|---|---|---|
| 19 | Meabh Carroll | 0 |
| 20 | Lorcan Hayes | 0 |
| 14 | Padraig Healy | 1 |
| 18 | Ronan Duffy | 1 |
| 6 | Darragh Nolan | 2 |
Two customers have 0. They would vanish with a plain JOIN.
Shop The INNER JOIN trap
Predict first: There are 20 customers. How many does this count?
Show the result without running
| customers_seen |
|---|
| 18 |
There are 20 customers. The inner join sees 18.
Music Songs nobody played
Show the result without running
| song_id | title |
|---|---|
| 20 | Soft Focus |
The anti-join: no match means the right side is NULL.
Jobs Companies with no offers
Show the result without running
| name |
|---|
| Zillmere Robotics |
Test a column that is never NULL in a real match, like the ID.
Shop Put right-table filters in ON
Show the result without running
| name | delivered_orders |
|---|---|
| Meabh Carroll | 0 |
| Lorcan Hayes | 0 |
| Grainne Lynch | 1 |
| Padraig Healy | 1 |
| Ronan Duffy | 1 |
The status test in ON keeps customers with no delivered orders.
Common mistake
A WHERE test on the right-hand table after a LEFT JOIN (WHERE o.status = 'delivered') removes the unmatched rows, so it acts as an INNER JOIN. Move it into ON. And use COUNT(o.order_id), not COUNT(*), or customers with no orders count as 1.
Hex and exams: "Customers who never ordered" is a favourite exam question. LEFT JOIN ... IS NULL or NOT EXISTS both work. Avoid NOT IN (subquery): if the subquery returns a NULL, you get no rows at all.
Try it yourself
App Which users never made a
first_post? Returnuser_id.Hint
Put
e.event_name = 'first_post'in the ON, then WHERE e.event_id IS NULL.Show the answer
Shop Every customer with their total units ordered (sum of quantity), showing 0 for customers with no orders. Return
nameandunits.Hint
LEFT JOIN, then COALESCE(SUM(o.quantity), 0).
Show the answer
16Joining three tablesLevel 3
Chain the joins one at a time. Each one needs its own ON.
SELECT a.x, b.y, c.z FROM table_a a JOIN table_b b ON b.a_id = a.a_id JOIN table_c c ON c.c_id = b.c_id;
New to this? SQL from zero: JOINs
Examples
Music Plays per artist
Show the result without running
| artist | plays |
|---|---|
| Mara Vale | 67 |
| The Gannets | 28 |
| Neon Curlew | 24 |
| Low Kettle | 22 |
| Driftwood Kids | 21 |
| Sally Gap | 4 |
| Brass Harbour | 4 |
Streams know the song. Songs know the artist.
Shop Who bought what in Galway
Show the result without running
| name | order_date | product | quantity |
|---|---|---|---|
| Sinead Moran | 2025-01-03 | Trail Runner Shoes | 1 |
| Sinead Moran | 2025-01-09 | Camping Stove | 2 |
| Niamh Kelly | 2025-01-13 | Puzzle 1000 | 1 |
| Niamh Kelly | 2025-01-14 | Cookbook: Brown Bread | 1 |
| Niamh Kelly | 2025-02-01 | Chef Knife | 1 |
| Sinead Moran | 2025-02-02 | Cast Iron Pan | 1 |
| Niamh Kelly | 2025-02-19 | Trail Runner Shoes | 1 |
| Niamh Kelly | 2025-03-01 | Atlas of Islands | 2 |
| Roisin Quinn | 2025-03-23 | Board Game: Harbour | 1 |
| Sinead Moran | 2025-04-14 | Chef Knife | 1 |
| Roisin Quinn | 2025-04-16 | Rain Jacket | 3 |
| Niamh Kelly | 2025-04-25 | Cookbook: Brown Bread | 2 |
| Niamh Kelly | 2025-05-14 | Rain Jacket | 3 |
| Roisin Quinn | 2025-06-14 | Camping Stove | 1 |
Start from the table that has one row per thing you want: here, orders.
Football The same table twice
Show the result without running
| match_date | home | home_goals | away_goals | away |
|---|---|---|---|---|
| 2024-08-03 | Shannon Celtic | 0 | 2 | Bogside Athletic |
| 2024-08-03 | Riverside Rovers | 2 | 2 | Claddagh Town |
| 2024-08-03 | Harbour United | 3 | 0 | Bogside Athletic |
| 2024-08-10 | Shannon Celtic | 1 | 0 | Northside Wanderers |
| 2024-08-10 | Harbour United | 2 | 2 | Riverside Rovers |
| 2024-08-10 | Harbour United | 1 | 2 | Shannon Celtic |
| 2024-08-17 | Northside Wanderers | 1 | 2 | Riverside Rovers |
| 2024-08-17 | Northside Wanderers | 0 | 1 | Harbour United |
Two aliases for one table: one for home, one for away.
Jobs Fan-out: wrong on purpose
Predict first: Are these numbers right? Compare with a count of each table alone.
Show the result without running
| name | offers | employees |
|---|---|---|
| Brightwell Analytics | 3 | 3 |
| Copperleaf Foods | 15 | 15 |
| Glenvarra Energy | 6 | 6 |
| Harbourlight Health | 10 | 10 |
| Kettlebrook Bank | 6 | 6 |
| Larkspur Freight | 12 | 12 |
| Pixelmoor Games | 6 | 6 |
| Quillstone Media | 6 | 6 |
| Saltmarsh Stores | 35 | 35 |
| Umberfield Software | 10 | 10 |
| Willowby Insurance | 12 | 12 |
| Zillmere Robotics | 0 | 2 |
Every offer pairs with every employee, so both counts are multiplied.
Common mistake
Fan-out. Joining two "many" tables to the same parent multiplies the rows. Count each one in its own CTE first, then join the counts. Or use COUNT(DISTINCT o.offer_id).
Hex and exams: Exam habit: alias every table and prefix every column (o.status, not status). It saves you from "ambiguous column" errors when two tables share a name.
Try it yourself
Music Total seconds played per genre. Return
genreandseconds.Hint
streams to songs to artists, SUM(st.seconds_played).
Show the answer
Shop Revenue (quantity times price) per customer city, delivered orders only, rounded to 2 decimals. Return
cityandrevenue.Hint
orders, customers and products. Keep the NULL city as its own row.
Show the answer
17Compare to the average: subqueries and self-joinsLevel 3
Work out a number in brackets, then compare each row to it.
SELECT * FROM table_name WHERE value > (SELECT AVG(value) FROM table_name);
New to this? SQL from zero: CTEs
Examples
Shop Products dearer than average
Show the result without running
| name | price |
|---|---|
| Rain Jacket | 120.0 |
| Trail Runner Shoes | 89.0 |
| Coffee Grinder | 75.0 |
| Chef Knife | 59.0 |
The bracket returns one number.
Jobs Above their own family's average
Show the result without running
| offer_id | job_family | base_salary |
|---|---|---|
| 3 | Product | 61000 |
| 5 | Data | 74000 |
| 9 | Sales | 42500 |
| 10 | Product | 73500 |
| 14 | Product | 58500 |
| 15 | Engineering | 69000 |
| 21 | Product | 57500 |
| 23 | Product | 85000 |
| 25 | Data | 64500 |
| 26 | Data | 83000 |
| 29 | Design | 64000 |
| 30 | Engineering | 63500 |
| 36 | Data | 57000 |
| 37 | Design | 68000 |
| 38 | Sales | 42000 |
| 41 | Design | 68500 |
| 43 | Design | 74000 |
| 44 | Data | 75000 |
| 45 | Product | 92000 |
A correlated subquery: it runs once for each row's family.
Music Listeners who played Mara Vale
Show the result without running
| name |
|---|
| Ada |
| Ben |
| Cara |
| Dev |
| Ella |
| Finn |
| Gia |
| Hugo |
| Isla |
| Kai |
| Lena |
| Milo |
| Nora |
IN with a subquery that returns a list.
App Self-join: same sign-up day
Show the result without running
| user_a | user_b | signup_date |
|---|---|---|
| 2 | 11 | 2025-01-07 |
| 9 | 12 | 2025-01-26 |
| 20 | 23 | 2025-02-11 |
| 25 | 35 | 2025-03-10 |
| 26 | 28 | 2025-03-24 |
| 32 | 33 | 2025-03-26 |
Join a table to itself. > stops each pair appearing twice.
Common mistake
A subquery after = or > must return one value. If it returns several, SQLite quietly uses the first and other databases error. Use IN for a list.
Hex and exams: "Above average" is ambiguous in exams. Say which average: the overall one or each group's own. Write it down in a comment.
Try it yourself
Music Songs longer than the average song length. Return
titleandlength_sec.Hint
Subquery on songs.
Show the answer
Shop Orders with a quantity above that customer's own average quantity. Return
order_id,customer_id,quantity.Hint
Correlated subquery: WHERE o2.customer_id = o.customer_id.
Show the answer
L4 Exam structure
CTEs, dates, ranking, de-duping.
18CTEs: one step at a timeLevel 4
Name a step with WITH, then query it like a table.
WITH step_one AS ( SELECT ... ), step_two AS ( SELECT ... FROM step_one ) SELECT ... FROM step_two;
New to this? SQL from zero: CTEs
Examples
Shop Spend per customer, then segments
Show the result without running
| segment | customers |
|---|---|
| high | 3 |
| low | 6 |
| medium | 9 |
Step one makes a number per customer. Step two buckets them.
Football A league table
Show the result without running
| name | played | points | goal_diff |
|---|---|---|---|
| Riverside Rovers | 9 | 18 | 8 |
| Claddagh Town | 9 | 17 | 1 |
| Harbour United | 10 | 15 | 6 |
| Shannon Celtic | 10 | 11 | -4 |
| Bogside Athletic | 7 | 9 | -5 |
| Northside Wanderers | 7 | 3 | -6 |
UNION ALL stacks home and away rows so each team has one row per match.
App Average of a count
Show the result without running
| avg_sessions | most |
|---|---|
| 2.8 | 8 |
You cannot write AVG(COUNT(*)). Count in one step, average in the next.
Jobs Company size, then offers
Show the result without running
| name | employees | offers |
|---|---|---|
| Brightwell Analytics | 1 | 3 |
| Copperleaf Foods | 3 | 5 |
| Harbourlight Health | 2 | 5 |
| Kettlebrook Bank | 2 | 3 |
| Pixelmoor Games | 2 | 3 |
| Quillstone Media | 3 | 2 |
| Glenvarra Energy | 3 | 2 |
| Saltmarsh Stores | 5 | 7 |
| Larkspur Freight | 2 | 6 |
| Umberfield Software | 2 | 5 |
| Willowby Insurance | 3 | 4 |
| Zillmere Robotics | 2 | NULL |
This is the fix for the fan-out in pattern 16.
Common mistake
Separate CTEs with a comma and write WITH only once. No comma before the final SELECT.
Hex and exams: In Hex you can build the same thing as separate cells. Cell 1 returns a dataframe you name spend. Cell 2 says SELECT ... FROM spend. That is easier to debug. Before you submit an exam, fold the cells into one query with WITH, so the grader can run it in one go.
-- Hex cell 1, output named: spend SELECT o.customer_id, SUM(o.quantity * p.price) AS total FROM orders o JOIN products p ON p.product_id = o.product_id WHERE o.status = 'delivered' GROUP BY o.customer_id; -- Hex cell 2 (dataframe SQL, runs on DuckDB) SELECT COUNT(*) AS big_spenders FROM spend WHERE total >= 300;
Try it yourself
Music Average number of streams per listener, counting only listeners who streamed. Round to 1 decimal.
Hint
CTE: streams per listener. Then AVG.
Show the answer
Jobs Count accepted offers per company. How many companies have 3 or more? One number.
Hint
CTE with GROUP BY company_id, then COUNT(*) WHERE accepted >= 3.
Show the answer
19Dates: by month, by weekday, days betweenLevel 4
Cut a date down to the part you want, then group by it.
-- SQLite (this page)
SELECT strftime('%Y-%m', date_col) AS month, COUNT(*)
FROM table_name GROUP BY month;
-- DuckDB (Hex)
SELECT date_trunc('month', date_col) AS month, COUNT(*)
FROM table_name GROUP BY month;New to this? SQL from zero: Dates
Examples
Shop Orders per month
Show the result without running
| month | orders |
|---|---|
| 2025-01 | 15 |
| 2025-02 | 12 |
| 2025-03 | 9 |
| 2025-04 | 15 |
| 2025-05 | 7 |
| 2025-06 | 12 |
%Y-%m keeps year and month, so it sorts in time order.
Music Streams by day of the week
Show the result without running
| weekday | streams |
|---|---|
| 0 | 23 |
| 1 | 22 |
| 2 | 24 |
| 3 | 24 |
| 4 | 28 |
| 5 | 26 |
| 6 | 23 |
In SQLite, %w gives 0 for Sunday up to 6 for Saturday.
Jobs Days from offer to acceptance
Show the result without running
| job_family | avg_days |
|---|---|
| Data | 6.2 |
| Design | 8.2 |
| Engineering | 5.8 |
| Product | 10.0 |
| Sales | 8.2 |
julianday turns a date into a day number, so you can subtract.
App Sign-ups by first day of the month
Show the result without running
| month_start | signups |
|---|---|
| 2025-01-01 | 12 |
| 2025-02-01 | 12 |
| 2025-03-01 | 12 |
The SQLite twin of DuckDB's date_trunc('month', ...).
Football Matches in the last 14 days of data
Show the result without running
| match_id | match_date |
|---|---|
| 22 | 2024-09-21 |
| 23 | 2024-09-21 |
| 24 | 2024-09-21 |
| 25 | 2024-09-28 |
| 26 | 2024-09-28 |
| 27 | 2024-09-28 |
| 28 | 2024-10-05 |
| 29 | 2024-10-05 |
| 30 | 2024-10-05 |
Exams say "last 14 days". Count back from the latest date in the data, not from today.
Common mistake
event_time BETWEEN '2025-01-01' AND '2025-01-31' misses everything after midnight on the 31st, because '2025-01-31 14:00' is bigger than '2025-01-31'. Use >= '2025-01-01' AND < '2025-02-01'.
Hex and exams: Dates are where SQLite and DuckDB differ most. See the table below. DuckDB's strftime takes the date first and the format second: the opposite of SQLite.
| Job | SQLite (this page) | DuckDB (Hex) |
|---|---|---|
| Month label | strftime('%Y-%m', d) | strftime(d, '%Y-%m') |
| First day of month | date(d, 'start of month') | date_trunc('month', d) |
| Days between | julianday(b) - julianday(a) | date_diff('day', a, b) |
| Day of week (0 = Sunday) | strftime('%w', d) | dayofweek(d) |
| Add 7 days | date(d, '+7 days') | d + INTERVAL 7 DAY |
| Text to date | already text | CAST(d AS DATE) |
Try it yourself
Shop Orders per month for April to June 2025. Return
month(as YYYY-MM) andorders.Hint
Filter with
>= '2025-04-01'and< '2025-07-01'.Show the answer
App How many
session_startevents happened in January 2025? One number. (event_timehas a time on it.)Hint
Use
< '2025-02-01'as the end.Show the answer
20ROW_NUMBER: latest or first per groupLevel 4
Number the rows inside each group, then keep number 1.
WITH ranked AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY group_column
ORDER BY date_column DESC
) AS rn
FROM table_name
)
SELECT * FROM ranked WHERE rn = 1;New to this? SQL from zero: Window functions
Examples
Music See the numbering first
Show the result without running
| listener_id | streamed_on | song_id | nth |
|---|---|---|---|
| 2 | 2025-03-01 | 12 | 1 |
| 2 | 2025-03-07 | 2 | 2 |
| 2 | 2025-03-08 | 5 | 3 |
| 2 | 2025-03-14 | 9 | 4 |
| 2 | 2025-03-19 | 5 | 5 |
| 2 | 2025-03-19 | 19 | 6 |
| 2 | 2025-03-26 | 17 | 7 |
| 2 | 2025-03-28 | 5 | 8 |
| 4 | 2025-03-08 | 8 | 1 |
| 4 | 2025-03-16 | 1 | 2 |
| 4 | 2025-03-19 | 13 | 3 |
| 4 | 2025-03-22 | 1 | 4 |
| 4 | 2025-03-25 | 5 | 5 |
| 4 | 2025-03-28 | 5 | 6 |
The count starts again at 1 for each listener.
Shop Each customer's most recent order
Show the result without running
| customer_id | order_id | order_date |
|---|---|---|
| 1 | 61 | 2025-06-04 |
| 2 | 50 | 2025-04-28 |
| 3 | 56 | 2025-05-14 |
| 4 | 66 | 2025-06-14 |
| 5 | 69 | 2025-06-24 |
| 6 | 58 | 2025-06-01 |
| 7 | 64 | 2025-06-11 |
| 8 | 65 | 2025-06-13 |
| 9 | 67 | 2025-06-14 |
| 10 | 55 | 2025-05-13 |
| 11 | 59 | 2025-06-01 |
| 12 | 53 | 2025-05-10 |
| 13 | 54 | 2025-05-10 |
| 14 | 13 | 2025-01-28 |
| 15 | 43 | 2025-04-14 |
| 16 | 68 | 2025-06-17 |
| 17 | 63 | 2025-06-09 |
| 18 | 30 | 2025-03-03 |
The classic. order_id DESC breaks ties on the same day.
App Each user's first session
Show the result without running
| user_id | first_session |
|---|---|
| 1 | 2025-01-21 20:18:00 |
| 2 | 2025-01-11 07:30:00 |
| 3 | 2025-01-03 11:42:00 |
| 4 | 2025-01-06 18:21:00 |
| 5 | 2025-01-27 17:41:00 |
| 6 | 2025-01-21 18:40:00 |
| 7 | 2025-01-24 10:42:00 |
| 8 | 2025-02-15 20:51:00 |
| 9 | 2025-02-01 07:47:00 |
| 10 | 2025-01-13 20:45:00 |
| 11 | 2025-02-08 12:56:00 |
| 12 | 2025-01-26 07:24:00 |
| 13 | 2025-03-05 08:11:00 |
| 14 | 2025-02-21 17:59:00 |
| 15 | 2025-03-21 13:49:00 |
| 16 | 2025-03-10 12:18:00 |
| 17 | 2025-03-12 10:51:00 |
| 18 | 2025-02-07 15:09:00 |
| 20 | 2025-03-10 19:05:00 |
| 21 | 2025-02-11 19:30:00 |
| 22 | 2025-03-13 17:09:00 |
| 23 | 2025-02-25 16:32:00 |
| 25 | 2025-04-01 21:37:00 |
| 26 | 2025-04-08 21:11:00 |
| 27 | 2025-04-02 08:16:00 |
| 28 | 2025-04-08 13:25:00 |
| 29 | 2025-04-14 07:26:00 |
| 30 | 2025-03-04 10:46:00 |
| 31 | 2025-03-23 20:40:00 |
| 32 | 2025-04-22 18:49:00 |
| 33 | 2025-03-28 18:24:00 |
| 34 | 2025-03-26 07:06:00 |
| 36 | 2025-03-25 14:41:00 |
ASC for first, DESC for latest.
Jobs Each company's top offer, with the details
Show the result without running
| company_id | offer_id | job_family | base_salary |
|---|---|---|---|
| 1 | 41 | Design | 68500 |
| 2 | 26 | Data | 83000 |
| 3 | 36 | Data | 57000 |
| 4 | 40 | Engineering | 52000 |
| 5 | 25 | Data | 64500 |
| 6 | 10 | Product | 73500 |
| 7 | 28 | Data | 54500 |
| 8 | 44 | Data | 75000 |
| 9 | 23 | Product | 85000 |
| 10 | 45 | Product | 92000 |
| 11 | 13 | Design | 43500 |
MAX() would give the salary. ROW_NUMBER gives the whole row that has it.
Common mistake
WHERE rn = 1 in the same SELECT that makes rn fails: window functions run after WHERE. Wrap it in a CTE. And always add a tie-breaker to the ORDER BY, or two runs can pick different rows.
Hex and exams: DuckDB (Hex) has QUALIFY, which filters on a window function with no CTE: ... QUALIFY ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) = 1. SQLite does not. Know both.
Try it yourself
Jobs Each job family's most recent offer by
offered_at. If two share a date, take the higheroffer_id. Returnjob_family,offer_id,offered_at.Hint
PARTITION BY job_family ORDER BY offered_at DESC, offer_id DESC.
Show the answer
Music Each listener's most recent stream. If two share a date, take the higher
stream_id. Returnlistener_id,song_id,streamed_on.Hint
Same shape as the shop example.
Show the answer
21RANK against DENSE_RANKLevel 4
Three ways to number rows. They only differ when there are ties.
SELECT value,
ROW_NUMBER() OVER (ORDER BY value DESC) AS row_num, -- 1,2,3,4
RANK() OVER (ORDER BY value DESC) AS rnk, -- 1,2,2,4
DENSE_RANK() OVER (ORDER BY value DESC) AS dense_rnk -- 1,2,2,3
FROM table_name;New to this? SQL from zero: Window functions
Examples
Jobs All three side by side
Predict first: Two offers share a salary. What happens to the rank after them?
Show the result without running
| offer_id | base_salary | row_num | rnk | dense_rnk |
|---|---|---|---|---|
| 45 | 92000 | 1 | 1 | 1 |
| 23 | 85000 | 2 | 2 | 2 |
| 10 | 73500 | 3 | 3 | 3 |
| 3 | 61000 | 4 | 4 | 4 |
| 14 | 58500 | 5 | 5 | 5 |
| 21 | 57500 | 6 | 6 | 6 |
| 4 | 53500 | 7 | 7 | 7 |
| 12 | 53500 | 8 | 7 | 7 |
| 18 | 48000 | 9 | 9 | 8 |
| 19 | 48000 | 10 | 9 | 8 |
| 24 | 44500 | 11 | 11 | 9 |
| 33 | 41000 | 12 | 12 | 10 |
| 11 | 40000 | 13 | 13 | 11 |
| 17 | 39500 | 14 | 14 | 12 |
Look at the two 53500s and the two 48000s.
Music Rank listeners by streams
Show the result without running
| listener_id | streams | rnk |
|---|---|---|
| 6 | 27 | 1 |
| 11 | 17 | 2 |
| 3 | 17 | 2 |
| 1 | 17 | 2 |
| 12 | 16 | 5 |
| 14 | 15 | 6 |
| 8 | 14 | 7 |
| 5 | 12 | 8 |
| 7 | 10 | 9 |
| 2 | 8 | 10 |
| 4 | 6 | 11 |
| 15 | 4 | 12 |
| 9 | 4 | 12 |
| 13 | 3 | 14 |
A window can sort by an aggregate. The window runs after GROUP BY.
Shop Rank inside each category
Show the result without running
| category | name | price | price_rank |
|---|---|---|---|
| Books | Atlas of Islands | 38.0 | 1 |
| Books | Cookbook: Brown Bread | 24.0 | 2 |
| Books | Novel: Low Tide | 14.99 | 3 |
| Games | Board Game: Harbour | 34.99 | 1 |
| Games | Puzzle 1000 | 18.0 | 2 |
| Games | Card Game: Gulls | 12.5 | 3 |
| Kitchen | Coffee Grinder | 75.0 | 1 |
| Kitchen | Chef Knife | 59.0 | 2 |
| Kitchen | Cast Iron Pan | 42.0 | 3 |
| Outdoor | Rain Jacket | 120.0 | 1 |
| Outdoor | Trail Runner Shoes | 89.0 | 2 |
| Outdoor | Camping Stove | 45.5 | 3 |
PARTITION BY restarts the ranking for each category.
Football Biggest home wins
Show the result without running
| match_id | margin | rnk |
|---|---|---|
| 3 | 3 | 1 |
| 17 | 3 | 1 |
| 10 | 2 | 2 |
| 20 | 2 | 2 |
| 4 | 1 | 3 |
| 11 | 1 | 3 |
| 12 | 1 | 3 |
| 13 | 1 | 3 |
| 14 | 1 | 3 |
| 19 | 1 | 3 |
| 21 | 1 | 3 |
| 23 | 1 | 3 |
| 26 | 1 | 3 |
Ties share a rank.
Common mistake
"Second highest salary" with ROW_NUMBER picks one of two tied rows. With RANK there may be no rank 2 at all. DENSE_RANK = 2 is usually what the question means.
Try it yourself
Jobs The second-highest distinct
base_salaryamong Data offers. One number.Hint
DENSE_RANK in a CTE, then WHERE = 2.
Show the answer
Music Rank listeners by number of streams with DENSE_RANK (most = 1). Return
listener_id,streams,rnk.Hint
Like the music example, with DENSE_RANK.
Show the answer
22Top N per groupLevel 4
ROW_NUMBER with PARTITION BY, then keep rn <= N.
WITH ranked AS (
SELECT group_column, item, value,
ROW_NUMBER() OVER (PARTITION BY group_column ORDER BY value DESC) AS rn
FROM ...
)
SELECT * FROM ranked WHERE rn <= 3;New to this? SQL from zero: Window functions
Examples
Shop Top 2 products by revenue in each category
Show the result without running
| category | name | revenue |
|---|---|---|
| Books | Atlas of Islands | 342.0 |
| Books | Cookbook: Brown Bread | 240.0 |
| Games | Board Game: Harbour | 174.95 |
| Games | Puzzle 1000 | 126.0 |
| Kitchen | Cast Iron Pan | 672.0 |
| Kitchen | Chef Knife | 295.0 |
| Outdoor | Rain Jacket | 840.0 |
| Outdoor | Camping Stove | 546.0 |
Two CTEs: total first, rank second.
Music Top 2 songs per genre
Show the result without running
| genre | title | plays |
|---|---|---|
| Electronic | Wild Garlic | 11 |
| Electronic | Blue Hour | 9 |
| Folk | Copper Sky | 14 |
| Folk | Night Bus | 8 |
| Indie | Salt Road | 14 |
| Indie | Wren Song | 11 |
| Jazz | Tin Roof | 3 |
| Jazz | Slow Rain | 1 |
| Pop | Glass Tide | 29 |
| Pop | Ferry Home | 18 |
A subquery in FROM works the same as a second CTE.
Jobs Two best-paid offers per industry
Show the result without running
| industry | offer_id | base_salary |
|---|---|---|
| Energy | 28 | 54500 |
| Energy | 42 | 44000 |
| Finance | 40 | 52000 |
| Finance | 13 | 43500 |
| Health | 36 | 57000 |
| Health | 8 | 48500 |
| Logistics | 23 | 85000 |
| Logistics | 14 | 58500 |
| Media | 10 | 73500 |
| Media | 4 | 53500 |
| Retail | 26 | 83000 |
| Retail | 44 | 75000 |
| Tech | 45 | 92000 |
| Tech | 43 | 74000 |
Join inside the CTE, rank, then filter.
Football Each team's biggest home win
Show the result without running
| home_team_id | match_id | margin |
|---|---|---|
| 1 | 13 | 1 |
| 2 | 3 | 3 |
| 3 | 10 | 2 |
| 4 | 11 | 1 |
| 5 | 4 | 1 |
| 6 | 12 | 1 |
Top 1 per group is top N with N = 1.
Common mistake
ORDER BY revenue DESC LIMIT 2 gives the top 2 overall, not the top 2 in each group. LIMIT never looks at groups.
Hex and exams: In DuckDB (Hex): QUALIFY ROW_NUMBER() OVER (PARTITION BY category ORDER BY revenue DESC) <= 2. If the question says "include ties", swap ROW_NUMBER for RANK.
Try it yourself
Jobs The two most recent hires (by
start_date) at each company. Returncompany_id,employee_id,start_date.Hint
PARTITION BY company_id ORDER BY start_date DESC, keep rn <= 2.
Show the answer
App For each platform, the 2 users with the most
session_startevents. Break ties by loweruser_id. Returnplatform,user_id,sessions.Hint
Count sessions per user (join app_users for platform), then rank inside platform.
Show the answer
23Finding and removing duplicatesLevel 4
Decide what makes two rows "the same", count them, then keep one.
-- find SELECT key_a, key_b, COUNT(*) AS copies FROM table_name GROUP BY key_a, key_b HAVING COUNT(*) > 1; -- keep one WITH r AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY key_a, key_b ORDER BY id) AS rn FROM table_name ) SELECT * FROM r WHERE rn = 1;
New to this? SQL from zero: Grain
Examples
Shop Find double-submitted orders
Show the result without running
| customer_id | product_id | order_date | quantity | copies |
|---|---|---|---|---|
| 5 | 5 | 2025-04-08 | 2 | 2 |
Same customer, product, day and quantity: almost certainly a double click.
Shop Keep one of each
Predict first: How many rows will be left?
Show the result without running
| orders_before | orders_after |
|---|---|
| 70 | 69 |
rn = 1 keeps the first copy. Everything else is a duplicate.
Jobs Duplicate offers
Show the result without running
| company_id | job_family | level | base_salary | offered_at | copies | offer_ids |
|---|---|---|---|---|---|---|
| 2 | Product | Junior | 48000 | 2023-07-27 | 2 | 18,19 |
GROUP_CONCAT lists the IDs so you can look at them. DuckDB calls it string_agg.
App An event logged twice
Show the result without running
| user_id | event_name | event_time | copies |
|---|---|---|---|
| 8 | onboarding_done | 2025-01-09 11:00:00 | 2 |
Duplicate events inflate every count built on top.
Music DISTINCT on a pair
Show the result without running
| streams | listener_song_pairs |
|---|---|
| 170 | 102 |
Repeat plays are not duplicates. Know your grain before you remove anything.
Common mistake
Removing rows that are not real duplicates. A listener playing a song twice is two plays. Write down the key that makes a row unique before you de-dupe.
Hex and exams: DuckDB (Hex) has SELECT DISTINCT ON (key) * and QUALIFY for this. In pandas: df.drop_duplicates(subset=[...]).
Try it yourself
App How many rows would
eventshave after removing exact duplicates (sameuser_id,event_name,event_time)? One number.Hint
COUNT(*) over a SELECT DISTINCT of those three columns.
Show the answer
Shop Total units ordered (sum of quantity) after removing double-submitted orders (same customer, product, date, quantity). One number.
Hint
ROW_NUMBER over the four key columns, keep rn = 1, then SUM.
Show the answer
L5 Analytics
Change, running totals, shares, funnels.
24LAG: change against the previous periodLevel 5
Bring the previous row's value onto this row, then subtract.
SELECT period, value,
LAG(value) OVER (ORDER BY period) AS previous,
value - LAG(value) OVER (ORDER BY period) AS change
FROM per_period_table;New to this? SQL from zero: Window functions
Examples
Shop Orders month on month
Predict first: What will prev be for January?
Show the result without running
| month | orders | prev | change |
|---|---|---|---|
| 2025-01 | 15 | NULL | NULL |
| 2025-02 | 12 | 15 | -3 |
| 2025-03 | 9 | 12 | -3 |
| 2025-04 | 15 | 9 | 6 |
| 2025-05 | 7 | 15 | -8 |
| 2025-06 | 12 | 7 | 5 |
Group to one row per month first, then LAG.
Music Week-on-week change in streams
Show the result without running
| week | streams | pct_change |
|---|---|---|
| 1 | 42 | NULL |
| 2 | 41 | -2.4 |
| 3 | 49 | 19.5 |
| 4 | 38 | -22.4 |
Percentage change is (now - before) / before. The data covers 1 to 28 March: four weeks.
App Days between a user's sessions
Show the result without running
| user_id | event_time | days_since_last |
|---|---|---|
| 1 | 2025-01-21 20:18:00 | NULL |
| 1 | 2025-02-06 20:14:00 | 16.0 |
| 1 | 2025-03-20 08:38:00 | 41.5 |
| 2 | 2025-01-11 07:30:00 | NULL |
| 2 | 2025-01-16 08:29:00 | 5.0 |
| 2 | 2025-01-21 08:52:00 | 5.0 |
| 2 | 2025-02-04 13:15:00 | 14.2 |
| 2 | 2025-02-16 20:56:00 | 12.3 |
| 2 | 2025-03-04 18:16:00 | 15.9 |
| 2 | 2025-03-17 07:54:00 | 12.6 |
| 3 | 2025-01-03 11:42:00 | NULL |
PARTITION BY keeps each user's gaps separate.
Shop LEAD looks forward
Show the result without running
| customer_id | order_date | next_order |
|---|---|---|
| 1 | 2025-01-19 | 2025-01-25 |
| 1 | 2025-01-25 | 2025-01-26 |
| 1 | 2025-01-26 | 2025-01-28 |
| 1 | 2025-01-28 | 2025-02-05 |
| 1 | 2025-02-05 | 2025-02-10 |
| 1 | 2025-02-10 | 2025-03-22 |
| 1 | 2025-03-22 | 2025-06-04 |
| 1 | 2025-06-04 | NULL |
| 2 | 2025-01-25 | 2025-01-29 |
| 2 | 2025-01-29 | 2025-02-02 |
| 2 | 2025-02-02 | 2025-04-05 |
| 2 | 2025-04-05 | 2025-04-09 |
| 2 | 2025-04-09 | 2025-04-28 |
| 2 | 2025-04-28 | NULL |
LEAD is LAG the other way. The last order has no next one.
Common mistake
The first row has no previous one, so LAG gives NULL. That is right: do not fill it with 0. And watch for a previous value of 0 when you divide.
Hex and exams: LAG and LEAD are the same in DuckDB. If a month has no rows at all, it is missing from the grouped table, so LAG compares with the month before it. Exams sometimes test that gap.
Try it yourself
Jobs Count offers per year (from
offered_at) and the change from the previous year. Returnyear,offers,change.Hint
strftime('%Y', ...) in a CTE, then LAG.
Show the answer
Music Streams per day for 1 to 7 March 2025, with the previous day's count. Return
day,streams,prev_day.Hint
GROUP BY streamed_on with a WHERE, then LAG(streams).
Show the answer
25Running totals with SUM OVERLevel 5
Add each row to everything before it.
SELECT period, value,
SUM(value) OVER (ORDER BY period) AS running_total
FROM per_period_table;New to this? SQL from zero: Window functions
Examples
Shop Cumulative revenue by month
Show the result without running
| month | revenue | year_to_date |
|---|---|---|
| 2025-01 | 613.99 | 613.99 |
| 2025-02 | 320.99 | 934.98 |
| 2025-03 | 418.43 | 1353.41 |
| 2025-04 | 991.0 | 2344.41 |
| 2025-05 | 899.5 | 3243.91 |
| 2025-06 | 490.47 | 3734.38 |
ORDER BY inside OVER makes it running. Without it you get the grand total on every row.
App Total users so far
Show the result without running
| signup_date | signups | users_so_far |
|---|---|---|
| 2025-01-01 | 1 | 1 |
| 2025-01-03 | 1 | 2 |
| 2025-01-07 | 2 | 4 |
| 2025-01-09 | 1 | 5 |
| 2025-01-13 | 1 | 6 |
| 2025-01-15 | 1 | 7 |
| 2025-01-16 | 1 | 8 |
| 2025-01-18 | 1 | 9 |
| 2025-01-21 | 1 | 10 |
| 2025-01-26 | 2 | 12 |
| 2025-02-01 | 1 | 13 |
| 2025-02-04 | 1 | 14 |
| 2025-02-05 | 1 | 15 |
| 2025-02-07 | 1 | 16 |
| 2025-02-09 | 1 | 17 |
| 2025-02-11 | 2 | 19 |
| 2025-02-13 | 1 | 20 |
| 2025-02-15 | 1 | 21 |
| 2025-02-16 | 1 | 22 |
| 2025-02-18 | 1 | 23 |
| 2025-02-26 | 1 | 24 |
| 2025-03-03 | 1 | 25 |
| 2025-03-07 | 1 | 26 |
| 2025-03-10 | 2 | 28 |
| 2025-03-15 | 1 | 29 |
| 2025-03-17 | 1 | 30 |
| 2025-03-23 | 1 | 31 |
| 2025-03-24 | 2 | 33 |
| 2025-03-25 | 1 | 34 |
| 2025-03-26 | 2 | 36 |
The last row should equal the size of the table.
Football Riverside Rovers' points, match by match
Show the result without running
| match_date | scored | conceded | points_so_far |
|---|---|---|---|
| 2024-08-03 | 2 | 2 | 1 |
| 2024-08-10 | 2 | 2 | 2 |
| 2024-08-17 | 2 | 1 | 8 |
| 2024-08-17 | 3 | 0 | 8 |
| 2024-08-31 | 2 | 1 | 11 |
| 2024-09-07 | 1 | 1 | 12 |
| 2024-09-14 | 2 | 1 | 15 |
| 2024-09-28 | 3 | 0 | 18 |
| 2024-09-28 | 1 | 2 | 18 |
A running total of a CASE.
Music Running plays per listener
Show the result without running
| listener_id | streamed_on | stream_id | plays_so_far |
|---|---|---|---|
| 4 | 2025-03-08 | 45 | 1 |
| 4 | 2025-03-16 | 91 | 2 |
| 4 | 2025-03-19 | 115 | 3 |
| 4 | 2025-03-22 | 133 | 4 |
| 4 | 2025-03-25 | 149 | 5 |
| 4 | 2025-03-28 | 164 | 6 |
ROWS BETWEEN ... counts row by row, even when two rows share a date.
Common mistake
With only ORDER BY date, rows on the same date are added together in one jump. Add a unique tie-breaker or ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW to go row by row.
Try it yourself
Jobs Offers per month in 2024 with a running count. Return
month(YYYY-MM),offers,running.Hint
Group by month in a CTE, then SUM(offers) OVER (ORDER BY month).
Show the answer
Shop For customer 1, each order's
order_id,order_dateand a running total ofquantity, ordered by date then order_id.Hint
SUM(quantity) OVER (ORDER BY order_date, order_id).
Show the answer
27Funnels and retentionLevel 5
Count distinct people at each step, then divide by the step before or the start.
SELECT COUNT(DISTINCT CASE WHEN step = 'a' THEN user_id END) AS step_a,
COUNT(DISTINCT CASE WHEN step = 'b' THEN user_id END) AS step_b
FROM events;New to this? SQL from zero: CASE WHEN
Examples
App Funnel step counts
Predict first: Each number should be smaller than the one before. Is it?
Show the result without running
| signed_up | onboarded | posted | subscribed |
|---|---|---|---|
| 36 | 30 | 17 | 10 |
CASE with no ELSE gives NULL, and COUNT(DISTINCT) skips NULLs.
App Funnel as rows with conversion
Show the result without running
| step | name | users | pct_of_start | pct_of_prev |
|---|---|---|---|---|
| 1 | signup | 36 | 100.0 | NULL |
| 2 | onboarding_done | 30 | 83.3 | 83.3 |
| 3 | first_post | 17 | 47.2 | 56.7 |
| 4 | subscribe | 10 | 27.8 | 58.8 |
A long shape that is easy to chart: one row per step.
App Retention by sign-up month
Show the result without running
| cohort | users | active_after_4_weeks | retention_pct |
|---|---|---|---|
| 2025-01 | 12 | 10 | 83.3 |
| 2025-02 | 12 | 10 | 83.3 |
| 2025-03 | 12 | 5 | 41.7 |
Cohort-lite: who was still using the app four weeks after joining.
Shop Repeat-purchase rate
Show the result without running
| buyers | repeat_buyers | repeat_pct |
|---|---|---|
| 18 | 16 | 88.9 |
A two-step funnel: bought once, bought again.
Music Week 1 listeners who came back in week 4
Show the result without running
| week1 | back_in_week4 |
|---|---|
| 12 | 11 |
Retention is a share of a starting group.
Common mistake
Counting events instead of people. A user who opens onboarding three times is still one user. Use COUNT(DISTINCT user_id) at every step.
Hex and exams: In Hex, put the long funnel result straight into a chart cell: a bar per step reads well. Strict funnels also check order of steps (signed up before posting). Say in a comment whether yours does.
Try it yourself
App For each sign-up month, how many users signed up and how many ever subscribed? Return
month(YYYY-MM),signups,subscribers.Hint
LEFT JOIN app_users to the subscribe events. Count distinct users on each side.
Show the answer
Shop Of the customers who ordered at all, what percentage ordered 3 or more times? One number, rounded to 1 decimal.
Hint
The repeat-purchase shape. The bottom of the fraction is buyers, not all customers.
Show the answer
28Median and percentilesLevel 5
The middle value. SQLite has no MEDIAN, so you build it. DuckDB has one.
-- DuckDB (Hex) SELECT MEDIAN(x), quantile_cont(x, 0.9) FROM t; -- SQLite: number the rows, take the middle one or two WITH s AS ( SELECT x, ROW_NUMBER() OVER (ORDER BY x) AS rn, COUNT(*) OVER () AS n FROM t WHERE x IS NOT NULL ) SELECT AVG(x) AS median FROM s WHERE rn IN ((n + 1) / 2, (n + 2) / 2);
New to this? SQL from zero: Median
Examples
Jobs Median salary
Show the result without running
| median_salary |
|---|
| 48500.0 |
Here whole-number division helps: with 44 rows it picks rows 22 and 23.
Music Mean against median
Predict first: Which will be bigger, the mean or the median?
Show the result without running
| mean | median |
|---|---|
| 189.9 | 192.0 |
Skips pull the mean down. The median is less moved by them.
Shop Median per group
Show the result without running
| category | median_price |
|---|---|
| Books | 24.0 |
| Games | 18.0 |
| Kitchen | 59.0 |
| Outdoor | 89.0 |
Add PARTITION BY to both windows and GROUP BY at the end.
App Quartiles with NTILE
Show the result without running
| quartile | users | low | high |
|---|---|---|---|
| 1 | 9 | 1 | 1 |
| 2 | 8 | 2 | 3 |
| 3 | 8 | 3 | 4 |
| 4 | 8 | 4 | 8 |
NTILE(4) splits sorted rows into four even buckets.
Common mistake
Using AVG when the question says "typical". One huge value drags the average. Salaries, prices and session counts are usually skewed, so the median is the honest middle.
Hex and exams: DuckDB (Hex): MEDIAN(base_salary), quantile_cont(base_salary, 0.9) for the 90th percentile. In pandas: df['base_salary'].median(). If an exam is in SQLite or MySQL, you need the window version above.
Try it yourself
Music The median song length (
length_sec) across all songs. One number.Hint
The jobs example, on the songs table.
Show the answer
Football The median total goals per played match. One number.
Hint
Filter out postponed matches first.
Show the answer
▸ Hex on exam day
- SQL cells become dataframes. Each SQL cell's result has a name. The next SQL cell can query it like a table:
SELECT * FROM spend. Rename them so you can tell them apart. - Two kinds of SQL. A cell pointed at a data connection uses that warehouse's SQL (Snowflake, BigQuery, Postgres and so on). A cell that queries dataframes runs on DuckDB. Check which one you are in before you reach for a date function.
- Chain while you work, fold before you submit. Build in small cells. Then give the final answer as one query with WITH, so a grader can run it in one go. Pattern 18 shows both.
- Practise without the AI. Hex has AI help built in. An exam may switch it off or ban it. Practise as if it is off.
- Cells run by what they depend on, not top to bottom. When you change a cell, Hex reruns the cells that use its result. Do not assume a cell lower on the page ran later. If a number looks stale, run everything again.
- Count rows after every join. A quick
SELECT COUNT(*)cell takes seconds and catches most mistakes. - Write your assumptions as comments. How you handled NULLs, ties and duplicates. Graders read them.
SQLite on this page against DuckDB in Hex
| Thing | SQLite (this page) | DuckDB (Hex dataframes) |
|---|---|---|
5 / 2 | 2 | 2.5 (use // for 2) |
| LIKE | ignores case for plain letters | case-sensitive; ILIKE ignores case |
| NULLs when sorting smallest first | first | last |
| Month from a date | strftime('%Y-%m', d) | date_trunc('month', d) |
| strftime | format first, date second | date first, format second |
| Median | build it with windows | MEDIAN(x), quantile_cont(x, 0.9) |
| Filter on a window function | wrap it in a CTE | QUALIFY |
| Column next to an aggregate, no GROUP BY | runs and picks a value | error |
| Text in "double quotes" | treated as text if no such column | always a column name |
| Group by every plain column | list them | GROUP BY ALL |
| Join values into a list | GROUP_CONCAT | string_agg |
▸ Mock exam: 10 questions
Give yourself 45 minutes. No AI, and no hints until you have had a real go. Each question mixes two or three patterns, like a real exam.
Shop Which month had the highest delivered revenue (quantity times price)? Return
month(YYYY-MM) andrevenuerounded to 2 decimals. One row.Hint
Join, filter on status, group by month, ORDER BY revenue DESC LIMIT 1.
Show the answer
Shop Names of customers who have never placed an order.
Hint
LEFT JOIN ... WHERE o.order_id IS NULL.
Show the answer
Music Each listener's favourite artist: the artist they streamed most. Break ties by lower
artist_id. Returnlistener_idandartist_id.Hint
Count per listener and artist in a CTE, then ROW_NUMBER per listener.
Show the answer
Football Which team has the most points (3 for a win, 1 for a draw) from played matches? Return
nameandpoints. One row.Hint
Stack home and away results with UNION ALL, as in the CTE pattern.
Show the answer
App Of users who finished onboarding, what percentage went on to make a first post? One number, rounded to 1 decimal.
Hint
Two COUNT(DISTINCT CASE ...) values, one divided by the other.
Show the answer
Jobs For each industry, the highest offer salary and the company that made it. Ties: lower
offer_id. Returnindustry,name,base_salary.Hint
Join offers to companies, ROW_NUMBER per industry.
Show the answer
Music Skip rate (streams under 30 seconds) for each plan, as a percentage rounded to 1 decimal. Return
planandskip_pct.Hint
Join to listeners, SUM(CASE ...) over COUNT(*).
Show the answer
Shop Which month had the biggest drop in order count compared with the month before? Return
monthandchange(a negative number). One row.Hint
Monthly counts, LAG, then ORDER BY change LIMIT 1.
Show the answer
Jobs Acceptance rate (status 'accepted') for companies that made at least 4 offers, rounded to 1 decimal. Return
company_id,offers,accept_pct.Hint
GROUP BY company_id, HAVING COUNT(*) >= 4, and a SUM(CASE ...) rate.
Show the answer
App Average number of sessions per user across all users, counting users with no sessions as 0. Rounded to 2 decimals.
Hint
LEFT JOIN app_users to session events, count per user, then AVG.
Show the answer
▸ Practice next
- SQL from zeroEvery idea explained slowly, with the same jobs tables.
- Python from zeropandas for the same kind of questions.
- SQL and Python practiceTake-home style tasks.
- Data interview questionsWhat gets asked, and how to answer.