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

  1. Read the pattern. One line and a template you can copy.
  2. Predict. Before you press Run, guess what comes back. How many rows? Any NULLs?
  3. Run it, then change it. Every box is editable. Reset puts it back.
  4. 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.

  1. 1SELECT, aliases and maths
  2. 2WHERE with AND, OR, IN, BETWEEN, LIKE
  3. 3Finding NULLs
  4. 4ORDER BY and LIMIT: top N
  5. 5DISTINCT

2Aggregation

Count, add up and group.

  1. 6COUNT, SUM, AVG, MIN, MAX
  2. 7GROUP BY
  3. 8COUNT(DISTINCT)
  4. 9HAVING against WHERE
  5. 10ROUND, percentages and the division trap

3Logic and joins

CASE, NULLs, and combining tables.

  1. 11CASE WHEN: buckets and labels
  2. 12CASE inside SUM: conditional counts and pivots
  3. 13COALESCE: fill in the blanks
  4. 14INNER JOIN
  5. 15LEFT JOIN and finding what is missing
  6. 16Joining three tables
  7. 17Compare to the average: subqueries and self-joins

4Exam structure

CTEs, dates, ranking, de-duping.

  1. 18CTEs: one step at a time
  2. 19Dates: by month, by weekday, days between
  3. 20ROW_NUMBER: latest or first per group
  4. 21RANK against DENSE_RANK
  5. 22Top N per group
  6. 23Finding and removing duplicates

5Analytics

Change, running totals, shares, funnels.

  1. 24LAG: change against the previous period
  2. 25Running totals with SUM OVER
  3. 26Share of total
  4. 27Funnels and retention
  5. 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
Result: 12 rows
namepriceprice_with_vat
Trail Runner Shoes89.0109.47
Camping Stove45.555.96
Rain Jacket120.0147.6
Board Game: Harbour34.9943.04
Puzzle 100018.022.14
Card Game: Gulls12.515.38
Chef Knife59.072.57
Cast Iron Pan42.051.66
Coffee Grinder75.092.25
Novel: Low Tide14.9918.44
Cookbook: Brown Bread24.029.52
Atlas of Islands38.046.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
Result: 30 rows
match_idmatch_datetotal_goals
12024-08-032
22024-08-034
32024-08-033
42024-08-101
52024-08-104
62024-08-103
72024-08-173
82024-08-171
92024-08-173
102024-08-242
112024-08-243
122024-08-241
132024-08-313
142024-08-313
152024-08-310
162024-09-077
172024-09-073
182024-09-072
192024-09-145
202024-09-144
212024-09-143
222024-09-211
232024-09-213
242024-09-212
252024-09-283
262024-09-283
272024-09-28NULL
282024-10-05NULL
292024-10-05NULL
302024-10-05NULL

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
Result: 20 rows
titlelength_secminutes_wrongminutes
Salt Road26544.4
Kite Weather20133.4
Half Light20333.4
Ferry Home19233.2
Glass Tide24944.2
Paper Moon30555.1
Long Grass15522.6
Copper Sky25944.3
Night Bus15322.5
Slow Rain15222.5
Tin Roof15922.6
Wild Garlic17222.9
Harbour Lights20733.5
Blue Hour20733.5
Hollow Hill19233.2
Static Bloom21833.6
Wren Song17522.9
Last Tram31055.2
Iron Bridge30055.0
Soft Focus21533.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
Result: 36 rows
user_idsegment
1web / DE
2android / IE
3web / IE
4web / DE
5web / UK
6web / DE
7android / US
8android / IE
9android / UK
10ios / UK
11android / IE
12android / IE
13ios / IE
14ios / UK
15ios / IE
16android / DE
17android / IE
18web / US
19web / DE
20web / DE
21android / US
22web / DE
23android / US
24ios / UK
25ios / US
26android / IE
27android / IE
28ios / IE
29ios / IE
30web / IE
31android / IE
32android / UK
33android / IE
34web / IE
35android / IE
36ios / IE

|| joins text. Handy for labels.

Jobs Monthly pay from a yearly salary

Show the result without running
Result: 45 rows
offer_idjob_familybase_salarymonthly
1Sales330002750.0
2Data370003083.0
3Product610005083.0
4Product535004458.0
5Data740006167.0
6Data415003458.0
7DesignNULLNULL
8Design485004042.0
9Sales425003542.0
10Product735006125.0
11Product400003333.0
12Product535004458.0
13Design435003625.0
14Product585004875.0
15Engineering690005750.0
16Design485004042.0
17Product395003292.0
18Product480004000.0
19Product480004000.0
20Design380003167.0
21Product575004792.0
22Data385003208.0
23Product850007083.0
24Product445003708.0
25Data645005375.0
26Data830006917.0
27Sales315002625.0
28Data545004542.0
29Design640005333.0
30Engineering635005292.0
31Sales340002833.0
32Design365003042.0
33Product410003417.0
34Sales295002458.0
35Data430003583.0
36Data570004750.0
37Design680005667.0
38Sales420003500.0
39Data450003750.0
40Engineering520004333.0
41Design685005708.0
42Engineering440003667.0
43Design740006167.0
44Data750006250.0
45Product920007667.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

  1. Music Show each listener's name and plan, with the plan column renamed subscription.

    Hint

    plan AS subscription. This one checks your column names too.

    Show the answer
  2. Shop Show each product's name and 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
Result: 22 rows
order_idcustomer_idquantitystatus
2152delivered
7172delivered
12132delivered
2832delivered
30182delivered
3153delivered
32112delivered
33132delivered
40122delivered
4152delivered
4493delivered
47102delivered
48162delivered
4932delivered
5252delivered
53122delivered
54133delivered
55103delivered
5633delivered
5863delivered
6112delivered
7052delivered

AND means both tests must pass.

Jobs Data or Design offers over 50,000

Show the result without running
Result: 10 rows
offer_idjob_familybase_salary
5Data74000
25Data64500
26Data83000
28Data54500
29Design64000
36Data57000
37Design68000
41Design68500
43Design74000
44Data75000

IN is a short way to write several ORs on one column.

Music Songs whose title starts with S

Show the result without running
Result: 4 rows
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
Result: 12 rows
match_idmatch_date
162024-09-07
172024-09-07
182024-09-07
192024-09-14
202024-09-14
212024-09-14
222024-09-21
232024-09-21
242024-09-21
252024-09-28
262024-09-28
272024-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
Result: 15 rows
user_idplatformcountry
2androidIE
8androidIE
11androidIE
12androidIE
13iosIE
15iosIE
17androidIE
26androidIE
27androidIE
28iosIE
29iosIE
31androidIE
33androidIE
35androidIE
36iosIE

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

  1. Jobs List offer_id and base_salary for Junior offers paying from 35,000 to 40,000, both ends included.

    Hint

    level = 'Junior' and BETWEEN.

    Show the answer
  2. Shop Find customers in Cork or Galway who signed up before 1 November 2024. Return name and city.

    Hint

    IN for the cities, then compare signup_date to '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
Result: 2 rows
customer_idname
6Darragh Nolan
14Padraig Healy

The simplest NULL check.

Football Matches not played yet

Show the result without running
Result: 4 rows
match_idmatch_date
272024-09-28
282024-10-05
292024-10-05
302024-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
Result: 0 rows
offer_id
No rows

Comparing anything to NULL gives unknown, so no row passes.

Music COUNT(*) against COUNT(column)

Show the result without running
Result: 1 row
listenerswith_country
1514

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
Result: 16 rows
user_idreferrer
2search
5friend
6search
10search
15search
16search
17friend
18search
22search
23search
25friend
26friend
27friend
31friend
32friend
36search

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

  1. Jobs Which companies have no city recorded? Return name.

    Hint

    The table is companies.

    Show the answer
  2. App List the user_id of 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
Result: 3 rows
nameprice
Rain Jacket120.0
Trail Runner Shoes89.0
Coffee Grinder75.0

DESC sorts biggest first. ASC (the default) sorts smallest first.

Music Five longest songs

Show the result without running
Result: 5 rows
titlelength_sec
Last Tram310
Paper Moon305
Iron Bridge300
Salt Road265
Copper Sky259

Top N is ORDER BY plus LIMIT.

Jobs Sort by two columns

Show the result without running
Result: 45 rows
offer_idjob_familybase_salary
26Data83000
44Data75000
5Data74000
25Data64500
36Data57000
28Data54500
39Data45000
35Data43000
6Data41500
22Data38500
2Data37000
43Design74000
41Design68500
37Design68000
29Design64000
8Design48500
16Design48500
13Design43500
20Design38000
32Design36500
7DesignNULL
15Engineering69000
30Engineering63500
40Engineering52000
42Engineering44000
45Product92000
23Product85000
10Product73500
3Product61000
14Product58500
21Product57500
4Product53500
12Product53500
18Product48000
19Product48000
24Product44500
33Product41000
11Product40000
17Product39500
9Sales42500
38Sales42000
31Sales34000
1Sales33000
27Sales31500
34Sales29500

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
Result: 6 rows
match_idgoals
27NULL
28NULL
29NULL
30NULL
150
41

SQLite puts NULLs first when sorting smallest first.

App Newest sign-ups

Show the result without running
Result: 5 rows
user_idsignup_date
322025-03-26
332025-03-26
272025-03-25
262025-03-24
282025-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

  1. Jobs Show the three most recent hires in employees: employee_id and start_date, newest first.

    Hint

    ORDER BY start_date DESC, then LIMIT.

    Show the answer
  2. Shop The four cheapest products: name and price, 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
Result: 6 rows
city
NULL
Cork
Dublin
Galway
Limerick
Waterford

NULL counts as one value and shows once.

Jobs Distinct pairs

Show the result without running
Result: 13 rows
job_familylevel
DataJunior
DataMid
DataSenior
DesignJunior
DesignMid
DesignSenior
EngineeringJunior
EngineeringMid
ProductJunior
ProductMid
ProductSenior
SalesJunior
SalesMid

DISTINCT works on the whole row: each family and level pair once.

Music Who streamed anything?

Show the result without running
Result: 14 rows
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
Result: 5 rows
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

  1. Shop Which product_ids have ever been ordered? One row each.

    Hint

    DISTINCT on the orders table.

    Show the answer
  2. App List each different country in app_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
Result: 1 row
ordersunitsfirst_orderlast_order
701002025-01-032025-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
Result: 1 row
offerswith_salaryavg_salary
454453159.0

One offer has no salary. AVG divides by 44, not 45.

Music Hours of music played

Show the result without running
Result: 1 row
hours
9.0

Divide by 3600.0, not 3600, to keep the decimals.

Football Goals per match

Show the result without running
Result: 1 row
homeawayavg_goals
38342.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

  1. 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
  2. Music What is the average song length in seconds, rounded to 1 decimal?

    Hint

    ROUND(AVG(...), 1) on the songs table.

    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
Result: 3 rows
statusorders
cancelled5
delivered57
returned8

Each different status becomes one row.

Music Most-played songs

Show the result without running
Result: 5 rows
song_idplays
529
418
814
114
612

GROUP BY, then ORDER BY the count, then LIMIT.

Jobs Two grouping columns

Show the result without running
Result: 13 rows
job_familyleveloffersavg_salary
DataJunior541000.0
DataMid255750.0
DataSenior474125.0
DesignJunior337250.0
DesignMid346833.0
DesignSenior468625.0
EngineeringJunior248000.0
EngineeringMid266250.0
ProductJunior643500.0
ProductMid556800.0
ProductSenior383500.0
SalesJunior432000.0
SalesMid242250.0

One row for each family and level pair.

App Users per platform

Show the result without running
Result: 3 rows
platformusers
android16
ios9
web11

The classic "how many in each" question.

Football Home goals by team

Show the result without running
Result: 6 rows
home_team_idhome_goals
212
47
17
36
54
62

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

  1. Shop How many customers live in each city? Return city and customers. Keep customers with no city as their own group.

    Hint

    GROUP BY city. Do not filter out the NULL.

    Show the answer
  2. Jobs How many employees does each company have? Return company_id and employees.

    Hint

    Group the employees table by company_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
Result: 1 row
streamslistenerssongs
1701419

170 rows, but far fewer people and songs.

Shop Orders and buyers per month

Show the result without running
Result: 6 rows
monthordersbuyers
2025-01159
2025-02128
2025-0399
2025-041511
2025-0576
2025-061210

Orders count rows. Buyers count people. (Dates are pattern 19.)

App Events against users

Show the result without running
Result: 5 rows
event_nameeventsusers
first_post1717
onboarding_done3130
session_start9333
signup3636
subscribe1010

Sessions: many events from fewer users.

Jobs Companies hiring in each family

Show the result without running
Result: 5 rows
job_familyofferscompanies
Data116
Design106
Engineering44
Product147
Sales64

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

  1. Shop How many different customers have placed at least one order? One number.

    Hint

    COUNT(DISTINCT ...) on orders.

    Show the answer
  2. Music For each song_id, how many different listeners played it? Return song_id and listeners.

    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
Result: 6 rows
customer_idorders
18
26
37
56
76
105

The test is on the count, so it must be HAVING.

Jobs Both in one query

Show the result without running
Result: 4 rows
job_familyacceptedavg_salary
Data1155727.0
Design955125.0
Engineering457125.0
Product957389.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
Result: 13 rows
song_idlisteners
19
25
35
47
511
66
77
86
96
129
145
178
195

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
Result: 2 rows
user_idsessions
218
27

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

  1. Jobs Which companies made more than four offers? Return company_id and offers.

    Hint

    GROUP BY company_id, HAVING COUNT(*) > 4.

    Show the answer
  2. Football Which home teams scored 7 or more goals at home? Return home_team_id and goals.

    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
Result: 1 row
whole_numberswith_decimalpct
00.071428571428571427.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
Result: 1 row
goalsplayedper_match_wrongper_match
722622.77

1.0 * turns the sum into a decimal before dividing.

Jobs Acceptance rate by family

Show the result without running
Result: 5 rows
job_familyofferspct_accepted
Data11100.0
Design1090.0
Engineering4100.0
Product1464.3
Sales683.3

COUNT(column) counts non-NULLs: here, offers with an accepted date.

App Share of users who subscribed

Show the result without running
Result: 1 row
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

  1. 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
  2. Jobs For each level, the percentage of offers that have an accepted_at date, rounded to 1 decimal. Return level and pct.

    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
Result: 12 rows
namepriceband
Card Game: Gulls12.5budget
Novel: Low Tide14.99budget
Puzzle 100018.0budget
Cookbook: Brown Bread24.0mid
Board Game: Harbour34.99mid
Atlas of Islands38.0mid
Cast Iron Pan42.0mid
Camping Stove45.5mid
Chef Knife59.0mid
Coffee Grinder75.0premium
Trail Runner Shoes89.0premium
Rain Jacket120.0premium

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
Result: 30 rows
match_idhome_goalsaway_goalsresult
102away win
222draw
330home win
410home win
522draw
612away win
712away win
801away win
903away win
1020home win
1121home win
1210home win
1321home win
1421home win
1500draw
1625away win
1730home win
1811draw
1932home win
2031home win
2121home win
2201away win
2321home win
2411draw
2503away win
2621home win
27NULLNULLnot played
28NULLNULLnot played
29NULLNULLnot played
30NULLNULLnot played

NULL fails every comparison, so postponed games fall through to ELSE.

Music Skips against listens

Show the result without running
Result: 2 rows
kindstreams
listen165
skip5

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
Result: 4 rows
bandoffers
NULL1
45k-60k12
60k+14
under 45k18

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

  1. App Label each user 'mobile' if platform is ios or android, otherwise 'desktop'. Return user_id and device.

    Hint

    WHEN platform IN ('ios', 'android').

    Show the answer
  2. Shop Label customers 'early' if they signed up before 1 November 2024, otherwise 'late'. Count each label. Return label and customers.

    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
Result: 18 rows
customer_idordersdeliverednot_delivered
1862
2642
3770
4321
5660
6220
7633
8431
9330
10541
11211
12440
13330
14110
15431
16220
17321
18110

Each CASE gives 1 or 0. SUM adds up the 1s.

Football Home record per team

Show the result without running
Result: 6 rows
home_team_idwondrawnlost
1220
2311
3202
4311
5212
6102

Postponed games count in none of the three.

App A yes/no flag per user

Show the result without running
Result: 36 rows
user_idsessionssubscribed
130
270
310
420
550
640
721
830
940
1050
1110
1241
1310
1421
1520
1621
1720
1830
1900
2030
2180
2230
2350
2400
2511
2620
2710
2811
2910
3041
3131
3210
3311
3430
3500
3631

MAX of a 1/0 CASE asks "did it ever happen?"

Jobs Pivot: levels across the top

Show the result without running
Result: 5 rows
job_familyjuniormidsenior
Data524
Design334
Engineering220
Product653
Sales420

Rows become columns. This is a pivot by hand.

Music Skip rate per listener

Show the result without running
Result: 14 rows
listener_idstreamsskip_pct
2812.5
71010.0
8147.1
14156.7
3175.9
1540.0
1330.0
12160.0
11170.0
940.0
6270.0
5120.0
460.0
1170.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

  1. Shop For each product_id, count delivered orders and returned orders. Return product_id, delivered, returned.

    Hint

    Two SUM(CASE ...) columns, GROUP BY product_id.

    Show the answer
  2. Music For each country in listeners, count premium and free listeners. Return country, 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
Result: 8 rows
order_iddiscountdiscount_filled
1NULL0
2NULL0
3NULL0
4NULL0
5NULL0
6NULL0
7NULL0
8NULL0

NULL becomes 0. Real values stay as they are.

Jobs A label for unknown cities

Show the result without running
Result: 12 rows
namecity
Brightwell AnalyticsDublin
Copperleaf FoodsCork
Harbourlight HealthGalway
Kettlebrook BankDublin
Pixelmoor GamesDublin
Quillstone MediaLondon
Glenvarra EnergyCork
Saltmarsh StoresLimerick
Larkspur FreightUnknown
Umberfield SoftwareLondon
Willowby InsuranceGalway
Zillmere RoboticsBerlin

Good for display and for grouping.

Music Group the unknowns with a name

Show the result without running
Result: 5 rows
countrylisteners
DE2
FR3
IE5
UK4
unknown1

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
Result: 1 row
avg_when_givenavg_per_order
6.671.14

Two different questions with two different answers.

App Missing referrer means direct

Show the result without running
Result: 4 rows
sourceusers
ad13
direct7
friend7
search9

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

  1. Shop Show each customer's name and email. Where the email is missing, show 'no email'.

    Hint

    COALESCE(email, 'no email').

    Show the answer
  2. 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
Result: 10 rows
order_idorder_datenamequantityline_total
12025-01-03Trail Runner Shoes189.0
22025-01-09Camping Stove291.0
32025-01-13Puzzle 1000118.0
42025-01-14Cookbook: Brown Bread124.0
52025-01-18Atlas of Islands138.0
62025-01-19Board Game: Harbour134.99
72025-01-21Cookbook: Brown Bread248.0
82025-01-25Cast Iron Pan142.0
92025-01-25Atlas of Islands138.0
102025-01-26Board Game: Harbour134.99

Short aliases (o, p) keep it readable.

Music Songs with their artist

Show the result without running
Result: 20 rows
titleartistgenre
Salt RoadThe GannetsIndie
Kite WeatherThe GannetsIndie
Half LightThe GannetsIndie
Ferry HomeMara ValePop
Glass TideMara ValePop
Paper MoonMara ValePop
Long GrassMara ValePop
Copper SkyLow KettleFolk
Night BusLow KettleFolk
Slow RainBrass HarbourJazz
Tin RoofBrass HarbourJazz
Wild GarlicNeon CurlewElectronic
Harbour LightsNeon CurlewElectronic
Blue HourNeon CurlewElectronic
Hollow HillSally GapFolk
Static BloomSally GapFolk
Wren SongDriftwood KidsIndie
Last TramDriftwood KidsIndie
Iron BridgeDriftwood KidsIndie
Soft FocusQuiet PylonAmbient

Many songs to one artist.

Jobs Tech offers with company names

Show the result without running
Result: 11 rows
namejob_familybase_salary
Umberfield SoftwareProduct61000
Pixelmoor GamesProduct53500
Umberfield SoftwareEngineering69000
Brightwell AnalyticsDesign38000
Pixelmoor GamesData64500
Brightwell AnalyticsDesign36500
Pixelmoor GamesSales29500
Umberfield SoftwareDesign68000
Brightwell AnalyticsDesign68500
Umberfield SoftwareDesign74000
Umberfield SoftwareProduct92000

Join first, then filter on either table.

Football Home team names

Show the result without running
Result: 8 rows
match_datehome_teamhome_goalsaway_goals
2024-08-03Shannon Celtic02
2024-08-03Riverside Rovers22
2024-08-03Harbour United30
2024-08-10Shannon Celtic10
2024-08-10Harbour United22
2024-08-10Harbour United12
2024-08-17Northside Wanderers12
2024-08-17Northside Wanderers01

The key can have a different name on each side.

Shop Revenue by category

Show the result without running
Result: 4 rows
categoryrevenue
Outdoor1742.0
Kitchen967.0
Books686.93
Games338.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

  1. Jobs For each employee at a Dublin company, show employee_id and the company name.

    Hint

    Join employees to companies, then WHERE c.city = 'Dublin'.

    Show the answer
  2. Music Count streams by listener plan. Return plan and streams.

    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
Result: 5 rows
customer_idnameorders
19Meabh Carroll0
20Lorcan Hayes0
14Padraig Healy1
18Ronan Duffy1
6Darragh Nolan2

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
Result: 1 row
customers_seen
18

There are 20 customers. The inner join sees 18.

Music Songs nobody played

Show the result without running
Result: 1 row
song_idtitle
20Soft Focus

The anti-join: no match means the right side is NULL.

Jobs Companies with no offers

Show the result without running
Result: 1 row
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
Result: 5 rows
namedelivered_orders
Meabh Carroll0
Lorcan Hayes0
Grainne Lynch1
Padraig Healy1
Ronan Duffy1

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

  1. App Which users never made a first_post? Return user_id.

    Hint

    Put e.event_name = 'first_post' in the ON, then WHERE e.event_id IS NULL.

    Show the answer
  2. Shop Every customer with their total units ordered (sum of quantity), showing 0 for customers with no orders. Return name and units.

    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
Result: 7 rows
artistplays
Mara Vale67
The Gannets28
Neon Curlew24
Low Kettle22
Driftwood Kids21
Sally Gap4
Brass Harbour4

Streams know the song. Songs know the artist.

Shop Who bought what in Galway

Show the result without running
Result: 14 rows
nameorder_dateproductquantity
Sinead Moran2025-01-03Trail Runner Shoes1
Sinead Moran2025-01-09Camping Stove2
Niamh Kelly2025-01-13Puzzle 10001
Niamh Kelly2025-01-14Cookbook: Brown Bread1
Niamh Kelly2025-02-01Chef Knife1
Sinead Moran2025-02-02Cast Iron Pan1
Niamh Kelly2025-02-19Trail Runner Shoes1
Niamh Kelly2025-03-01Atlas of Islands2
Roisin Quinn2025-03-23Board Game: Harbour1
Sinead Moran2025-04-14Chef Knife1
Roisin Quinn2025-04-16Rain Jacket3
Niamh Kelly2025-04-25Cookbook: Brown Bread2
Niamh Kelly2025-05-14Rain Jacket3
Roisin Quinn2025-06-14Camping Stove1

Start from the table that has one row per thing you want: here, orders.

Football The same table twice

Show the result without running
Result: 8 rows
match_datehomehome_goalsaway_goalsaway
2024-08-03Shannon Celtic02Bogside Athletic
2024-08-03Riverside Rovers22Claddagh Town
2024-08-03Harbour United30Bogside Athletic
2024-08-10Shannon Celtic10Northside Wanderers
2024-08-10Harbour United22Riverside Rovers
2024-08-10Harbour United12Shannon Celtic
2024-08-17Northside Wanderers12Riverside Rovers
2024-08-17Northside Wanderers01Harbour 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
Result: 12 rows
nameoffersemployees
Brightwell Analytics33
Copperleaf Foods1515
Glenvarra Energy66
Harbourlight Health1010
Kettlebrook Bank66
Larkspur Freight1212
Pixelmoor Games66
Quillstone Media66
Saltmarsh Stores3535
Umberfield Software1010
Willowby Insurance1212
Zillmere Robotics02

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

  1. Music Total seconds played per genre. Return genre and seconds.

    Hint

    streams to songs to artists, SUM(st.seconds_played).

    Show the answer
  2. Shop Revenue (quantity times price) per customer city, delivered orders only, rounded to 2 decimals. Return city and revenue.

    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
Result: 4 rows
nameprice
Rain Jacket120.0
Trail Runner Shoes89.0
Coffee Grinder75.0
Chef Knife59.0

The bracket returns one number.

Jobs Above their own family's average

Show the result without running
Result: 19 rows
offer_idjob_familybase_salary
3Product61000
5Data74000
9Sales42500
10Product73500
14Product58500
15Engineering69000
21Product57500
23Product85000
25Data64500
26Data83000
29Design64000
30Engineering63500
36Data57000
37Design68000
38Sales42000
41Design68500
43Design74000
44Data75000
45Product92000

A correlated subquery: it runs once for each row's family.

Music Listeners who played Mara Vale

Show the result without running
Result: 13 rows
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
Result: 6 rows
user_auser_bsignup_date
2112025-01-07
9122025-01-26
20232025-02-11
25352025-03-10
26282025-03-24
32332025-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

  1. Music Songs longer than the average song length. Return title and length_sec.

    Hint

    Subquery on songs.

    Show the answer
  2. 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
Result: 3 rows
segmentcustomers
high3
low6
medium9

Step one makes a number per customer. Step two buckets them.

Football A league table

Show the result without running
Result: 6 rows
nameplayedpointsgoal_diff
Riverside Rovers9188
Claddagh Town9171
Harbour United10156
Shannon Celtic1011-4
Bogside Athletic79-5
Northside Wanderers73-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
Result: 1 row
avg_sessionsmost
2.88

You cannot write AVG(COUNT(*)). Count in one step, average in the next.

Jobs Company size, then offers

Show the result without running
Result: 12 rows
nameemployeesoffers
Brightwell Analytics13
Copperleaf Foods35
Harbourlight Health25
Kettlebrook Bank23
Pixelmoor Games23
Quillstone Media32
Glenvarra Energy32
Saltmarsh Stores57
Larkspur Freight26
Umberfield Software25
Willowby Insurance34
Zillmere Robotics2NULL

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

  1. 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
  2. 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
Result: 6 rows
monthorders
2025-0115
2025-0212
2025-039
2025-0415
2025-057
2025-0612

%Y-%m keeps year and month, so it sorts in time order.

Music Streams by day of the week

Show the result without running
Result: 7 rows
weekdaystreams
023
122
224
324
428
526
623

In SQLite, %w gives 0 for Sunday up to 6 for Saturday.

Jobs Days from offer to acceptance

Show the result without running
Result: 5 rows
job_familyavg_days
Data6.2
Design8.2
Engineering5.8
Product10.0
Sales8.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
Result: 3 rows
month_startsignups
2025-01-0112
2025-02-0112
2025-03-0112

The SQLite twin of DuckDB's date_trunc('month', ...).

Football Matches in the last 14 days of data

Show the result without running
Result: 9 rows
match_idmatch_date
222024-09-21
232024-09-21
242024-09-21
252024-09-28
262024-09-28
272024-09-28
282024-10-05
292024-10-05
302024-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.

JobSQLite (this page)DuckDB (Hex)
Month labelstrftime('%Y-%m', d)strftime(d, '%Y-%m')
First day of monthdate(d, 'start of month')date_trunc('month', d)
Days betweenjulianday(b) - julianday(a)date_diff('day', a, b)
Day of week (0 = Sunday)strftime('%w', d)dayofweek(d)
Add 7 daysdate(d, '+7 days')d + INTERVAL 7 DAY
Text to datealready textCAST(d AS DATE)

Try it yourself

  1. Shop Orders per month for April to June 2025. Return month (as YYYY-MM) and orders.

    Hint

    Filter with >= '2025-04-01' and < '2025-07-01'.

    Show the answer
  2. App How many session_start events happened in January 2025? One number. (event_time has 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
Result: 14 rows
listener_idstreamed_onsong_idnth
22025-03-01121
22025-03-0722
22025-03-0853
22025-03-1494
22025-03-1955
22025-03-19196
22025-03-26177
22025-03-2858
42025-03-0881
42025-03-1612
42025-03-19133
42025-03-2214
42025-03-2555
42025-03-2856

The count starts again at 1 for each listener.

Shop Each customer's most recent order

Show the result without running
Result: 18 rows
customer_idorder_idorder_date
1612025-06-04
2502025-04-28
3562025-05-14
4662025-06-14
5692025-06-24
6582025-06-01
7642025-06-11
8652025-06-13
9672025-06-14
10552025-05-13
11592025-06-01
12532025-05-10
13542025-05-10
14132025-01-28
15432025-04-14
16682025-06-17
17632025-06-09
18302025-03-03

The classic. order_id DESC breaks ties on the same day.

App Each user's first session

Show the result without running
Result: 33 rows
user_idfirst_session
12025-01-21 20:18:00
22025-01-11 07:30:00
32025-01-03 11:42:00
42025-01-06 18:21:00
52025-01-27 17:41:00
62025-01-21 18:40:00
72025-01-24 10:42:00
82025-02-15 20:51:00
92025-02-01 07:47:00
102025-01-13 20:45:00
112025-02-08 12:56:00
122025-01-26 07:24:00
132025-03-05 08:11:00
142025-02-21 17:59:00
152025-03-21 13:49:00
162025-03-10 12:18:00
172025-03-12 10:51:00
182025-02-07 15:09:00
202025-03-10 19:05:00
212025-02-11 19:30:00
222025-03-13 17:09:00
232025-02-25 16:32:00
252025-04-01 21:37:00
262025-04-08 21:11:00
272025-04-02 08:16:00
282025-04-08 13:25:00
292025-04-14 07:26:00
302025-03-04 10:46:00
312025-03-23 20:40:00
322025-04-22 18:49:00
332025-03-28 18:24:00
342025-03-26 07:06:00
362025-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
Result: 11 rows
company_idoffer_idjob_familybase_salary
141Design68500
226Data83000
336Data57000
440Engineering52000
525Data64500
610Product73500
728Data54500
844Data75000
923Product85000
1045Product92000
1113Design43500

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

  1. Jobs Each job family's most recent offer by offered_at. If two share a date, take the higher offer_id. Return job_family, offer_id, offered_at.

    Hint

    PARTITION BY job_family ORDER BY offered_at DESC, offer_id DESC.

    Show the answer
  2. Music Each listener's most recent stream. If two share a date, take the higher stream_id. Return listener_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
Result: 14 rows
offer_idbase_salaryrow_numrnkdense_rnk
4592000111
2385000222
1073500333
361000444
1458500555
2157500666
453500777
1253500877
1848000998
19480001098
244450011119
3341000121210
1140000131311
1739500141412

Look at the two 53500s and the two 48000s.

Music Rank listeners by streams

Show the result without running
Result: 14 rows
listener_idstreamsrnk
6271
11172
3172
1172
12165
14156
8147
5128
7109
2810
4611
15412
9412
13314

A window can sort by an aggregate. The window runs after GROUP BY.

Shop Rank inside each category

Show the result without running
Result: 12 rows
categorynamepriceprice_rank
BooksAtlas of Islands38.01
BooksCookbook: Brown Bread24.02
BooksNovel: Low Tide14.993
GamesBoard Game: Harbour34.991
GamesPuzzle 100018.02
GamesCard Game: Gulls12.53
KitchenCoffee Grinder75.01
KitchenChef Knife59.02
KitchenCast Iron Pan42.03
OutdoorRain Jacket120.01
OutdoorTrail Runner Shoes89.02
OutdoorCamping Stove45.53

PARTITION BY restarts the ranking for each category.

Football Biggest home wins

Show the result without running
Result: 13 rows
match_idmarginrnk
331
1731
1022
2022
413
1113
1213
1313
1413
1913
2113
2313
2613

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

  1. Jobs The second-highest distinct base_salary among Data offers. One number.

    Hint

    DENSE_RANK in a CTE, then WHERE = 2.

    Show the answer
  2. 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
Result: 8 rows
categorynamerevenue
BooksAtlas of Islands342.0
BooksCookbook: Brown Bread240.0
GamesBoard Game: Harbour174.95
GamesPuzzle 1000126.0
KitchenCast Iron Pan672.0
KitchenChef Knife295.0
OutdoorRain Jacket840.0
OutdoorCamping Stove546.0

Two CTEs: total first, rank second.

Music Top 2 songs per genre

Show the result without running
Result: 10 rows
genretitleplays
ElectronicWild Garlic11
ElectronicBlue Hour9
FolkCopper Sky14
FolkNight Bus8
IndieSalt Road14
IndieWren Song11
JazzTin Roof3
JazzSlow Rain1
PopGlass Tide29
PopFerry Home18

A subquery in FROM works the same as a second CTE.

Jobs Two best-paid offers per industry

Show the result without running
Result: 14 rows
industryoffer_idbase_salary
Energy2854500
Energy4244000
Finance4052000
Finance1343500
Health3657000
Health848500
Logistics2385000
Logistics1458500
Media1073500
Media453500
Retail2683000
Retail4475000
Tech4592000
Tech4374000

Join inside the CTE, rank, then filter.

Football Each team's biggest home win

Show the result without running
Result: 6 rows
home_team_idmatch_idmargin
1131
233
3102
4111
541
6121

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

  1. Jobs The two most recent hires (by start_date) at each company. Return company_id, employee_id, start_date.

    Hint

    PARTITION BY company_id ORDER BY start_date DESC, keep rn <= 2.

    Show the answer
  2. App For each platform, the 2 users with the most session_start events. Break ties by lower user_id. Return platform, 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
Result: 1 row
customer_idproduct_idorder_datequantitycopies
552025-04-0822

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
Result: 1 row
orders_beforeorders_after
7069

rn = 1 keeps the first copy. Everything else is a duplicate.

Jobs Duplicate offers

Show the result without running
Result: 1 row
company_idjob_familylevelbase_salaryoffered_atcopiesoffer_ids
2ProductJunior480002023-07-27218,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
Result: 1 row
user_idevent_nameevent_timecopies
8onboarding_done2025-01-09 11:00:002

Duplicate events inflate every count built on top.

Music DISTINCT on a pair

Show the result without running
Result: 1 row
streamslistener_song_pairs
170102

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

  1. App How many rows would events have after removing exact duplicates (same user_id, event_name, event_time)? One number.

    Hint

    COUNT(*) over a SELECT DISTINCT of those three columns.

    Show the answer
  2. 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
Result: 6 rows
monthordersprevchange
2025-0115NULLNULL
2025-021215-3
2025-03912-3
2025-041596
2025-05715-8
2025-061275

Group to one row per month first, then LAG.

Music Week-on-week change in streams

Show the result without running
Result: 4 rows
weekstreamspct_change
142NULL
241-2.4
34919.5
438-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
Result: 11 rows
user_idevent_timedays_since_last
12025-01-21 20:18:00NULL
12025-02-06 20:14:0016.0
12025-03-20 08:38:0041.5
22025-01-11 07:30:00NULL
22025-01-16 08:29:005.0
22025-01-21 08:52:005.0
22025-02-04 13:15:0014.2
22025-02-16 20:56:0012.3
22025-03-04 18:16:0015.9
22025-03-17 07:54:0012.6
32025-01-03 11:42:00NULL

PARTITION BY keeps each user's gaps separate.

Shop LEAD looks forward

Show the result without running
Result: 14 rows
customer_idorder_datenext_order
12025-01-192025-01-25
12025-01-252025-01-26
12025-01-262025-01-28
12025-01-282025-02-05
12025-02-052025-02-10
12025-02-102025-03-22
12025-03-222025-06-04
12025-06-04NULL
22025-01-252025-01-29
22025-01-292025-02-02
22025-02-022025-04-05
22025-04-052025-04-09
22025-04-092025-04-28
22025-04-28NULL

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

  1. Jobs Count offers per year (from offered_at) and the change from the previous year. Return year, offers, change.

    Hint

    strftime('%Y', ...) in a CTE, then LAG.

    Show the answer
  2. 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
Result: 6 rows
monthrevenueyear_to_date
2025-01613.99613.99
2025-02320.99934.98
2025-03418.431353.41
2025-04991.02344.41
2025-05899.53243.91
2025-06490.473734.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
Result: 30 rows
signup_datesignupsusers_so_far
2025-01-0111
2025-01-0312
2025-01-0724
2025-01-0915
2025-01-1316
2025-01-1517
2025-01-1618
2025-01-1819
2025-01-21110
2025-01-26212
2025-02-01113
2025-02-04114
2025-02-05115
2025-02-07116
2025-02-09117
2025-02-11219
2025-02-13120
2025-02-15121
2025-02-16122
2025-02-18123
2025-02-26124
2025-03-03125
2025-03-07126
2025-03-10228
2025-03-15129
2025-03-17130
2025-03-23131
2025-03-24233
2025-03-25134
2025-03-26236

The last row should equal the size of the table.

Football Riverside Rovers' points, match by match

Show the result without running
Result: 9 rows
match_datescoredconcededpoints_so_far
2024-08-03221
2024-08-10222
2024-08-17218
2024-08-17308
2024-08-312111
2024-09-071112
2024-09-142115
2024-09-283018
2024-09-281218

A running total of a CASE.

Music Running plays per listener

Show the result without running
Result: 6 rows
listener_idstreamed_onstream_idplays_so_far
42025-03-08451
42025-03-16912
42025-03-191153
42025-03-221334
42025-03-251495
42025-03-281646

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

  1. 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
  2. Shop For customer 1, each order's order_id, order_date and a running total of quantity, ordered by date then order_id.

    Hint

    SUM(quantity) OVER (ORDER BY order_date, order_id).

    Show the answer
26Share of totalLevel 5

Divide each group by the sum of all groups, using SUM(...) OVER ().

SELECT group_column,
       COUNT(*) AS n,
       ROUND(100.0 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS pct
FROM table_name
GROUP BY group_column;

New to this? SQL from zero: Window functions

Examples

Shop Revenue share by category

Show the result without running
Result: 4 rows
categoryrevenuepct
Outdoor1742.046.6
Kitchen967.025.9
Books686.9318.4
Games338.459.1

OVER () with nothing inside means "all rows".

Music Share of plays by genre

Predict first: What should the pct column add up to?

Show the result without running
Result: 5 rows
genreplayspct
Pop6739.4
Indie4928.8
Folk2615.3
Electronic2414.1
Jazz42.4

SUM(COUNT(*)) OVER () works because the window runs after GROUP BY.

App Share within each group

Show the result without running
Result: 11 rows
platformcountryuserspct_of_platform
androidIE1062.5
androidUS318.8
androidUK212.5
androidDE16.3
iosIE555.6
iosUK333.3
iosUS111.1
webDE654.5
webIE327.3
webUK19.1
webUS19.1

PARTITION BY makes it a share of each platform, not of everything.

Jobs Offers share by industry

Show the result without running
Result: 7 rows
industryofferspct
Retail1226.7
Tech1124.4
Finance715.6
Logistics613.3
Health511.1
Energy24.4
Media24.4

Same pattern on joined data.

Common mistake

Leaving out 100.0: COUNT(*) / SUM(COUNT(*)) OVER () is whole-number division in SQLite and gives 0 for every row.

Try it yourself

  1. Music Percentage of listeners in each country, rounded to 1 decimal. Keep the unknown country as its own row. Return country, listeners, pct.

    Hint

    GROUP BY country with SUM(COUNT(*)) OVER ().

    Show the answer
  2. Shop Each order status as a percentage of all orders, rounded to 1 decimal. Return status, orders, pct.

    Hint

    Same shape on the orders table.

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

CASE with no ELSE gives NULL, and COUNT(DISTINCT) skips NULLs.

App Funnel as rows with conversion

Show the result without running
Result: 4 rows
stepnameuserspct_of_startpct_of_prev
1signup36100.0NULL
2onboarding_done3083.383.3
3first_post1747.256.7
4subscribe1027.858.8

A long shape that is easy to chart: one row per step.

App Retention by sign-up month

Show the result without running
Result: 3 rows
cohortusersactive_after_4_weeksretention_pct
2025-01121083.3
2025-02121083.3
2025-0312541.7

Cohort-lite: who was still using the app four weeks after joining.

Shop Repeat-purchase rate

Show the result without running
Result: 1 row
buyersrepeat_buyersrepeat_pct
181688.9

A two-step funnel: bought once, bought again.

Music Week 1 listeners who came back in week 4

Show the result without running
Result: 1 row
week1back_in_week4
1211

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

  1. 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
  2. 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
Result: 1 row
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
Result: 1 row
meanmedian
189.9192.0

Skips pull the mean down. The median is less moved by them.

Shop Median per group

Show the result without running
Result: 4 rows
categorymedian_price
Books24.0
Games18.0
Kitchen59.0
Outdoor89.0

Add PARTITION BY to both windows and GROUP BY at the end.

App Quartiles with NTILE

Show the result without running
Result: 4 rows
quartileuserslowhigh
1911
2823
3834
4848

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

  1. Music The median song length (length_sec) across all songs. One number.

    Hint

    The jobs example, on the songs table.

    Show the answer
  2. Football The median total goals per played match. One number.

    Hint

    Filter out postponed matches first.

    Show the answer

▸ Hex on exam day

SQLite on this page against DuckDB in Hex

ThingSQLite (this page)DuckDB (Hex dataframes)
5 / 222.5 (use // for 2)
LIKEignores case for plain letterscase-sensitive; ILIKE ignores case
NULLs when sorting smallest firstfirstlast
Month from a datestrftime('%Y-%m', d)date_trunc('month', d)
strftimeformat first, date seconddate first, format second
Medianbuild it with windowsMEDIAN(x), quantile_cont(x, 0.9)
Filter on a window functionwrap it in a CTEQUALIFY
Column next to an aggregate, no GROUP BYruns and picks a valueerror
Text in "double quotes"treated as text if no such columnalways a column name
Group by every plain columnlist themGROUP BY ALL
Join values into a listGROUP_CONCATstring_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.

0 of 10 correct so far
  1. Shop Which month had the highest delivered revenue (quantity times price)? Return month (YYYY-MM) and revenue rounded to 2 decimals. One row.

    Hint

    Join, filter on status, group by month, ORDER BY revenue DESC LIMIT 1.

    Show the answer
  2. Shop Names of customers who have never placed an order.

    Hint

    LEFT JOIN ... WHERE o.order_id IS NULL.

    Show the answer
  3. Music Each listener's favourite artist: the artist they streamed most. Break ties by lower artist_id. Return listener_id and artist_id.

    Hint

    Count per listener and artist in a CTE, then ROW_NUMBER per listener.

    Show the answer
  4. Football Which team has the most points (3 for a win, 1 for a draw) from played matches? Return name and points. One row.

    Hint

    Stack home and away results with UNION ALL, as in the CTE pattern.

    Show the answer
  5. 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
  6. Jobs For each industry, the highest offer salary and the company that made it. Ties: lower offer_id. Return industry, name, base_salary.

    Hint

    Join offers to companies, ROW_NUMBER per industry.

    Show the answer
  7. Music Skip rate (streams under 30 seconds) for each plan, as a percentage rounded to 1 decimal. Return plan and skip_pct.

    Hint

    Join to listeners, SUM(CASE ...) over COUNT(*).

    Show the answer
  8. Shop Which month had the biggest drop in order count compared with the month before? Return month and change (a negative number). One row.

    Hint

    Monthly counts, LAG, then ORDER BY change LIMIT 1.

    Show the answer
  9. 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
  10. 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