SQL from zero

What you'll learn: how to ask a database questions in SQL, from your first query to window functions, with practice tables you can query right here on the page.

  1. Tables and SQL
  2. Practice data
  3. SELECT, FROM
  4. WHERE
  5. NULL
  6. ORDER BY, LIMIT
  7. DISTINCT
  8. COUNT, SUM, AVG
  9. GROUP BY
  10. HAVING
  11. CASE WHEN
  12. JOINs
  13. Grain
  14. Dates
  15. CTEs (WITH)
  16. Window functions
  17. Median, percentiles
  18. Long queries
  19. 10 practice questions
  20. Glossary

1 Data, tables and what SQL is

Data is just facts that someone wrote down. A list of job offers is data: which company made the offer, what the job was, how much it paid and when.

Think of a spreadsheet. A table is one sheet in that spreadsheet: a grid with headings along the top. Here is a small piece of one.

A table called offers (first 3 rows): 3 rows
offer_idcompany_idjob_familybase_salary
14Sales33000
211Data37000
310Product61000

SQL stands for Structured Query Language. People say it as letters, “S-Q-L”, or as “sequel”. Both are fine. It is the language you use to ask a database questions.

A query is one of those questions, written in SQL. You send it to the database. The database sends back a result, which is itself a small table.

Who uses it? Analysts asking “what is the average salary for data jobs this year?”. Apps storing users, scores and messages (most phone apps carry a small database inside them). Finance teams adding up sales. Dashboards in tools like Tableau or Looker, which write SQL for you behind the scenes. If a job title has “data” or “analyst” in it, SQL is almost always part of the work.

The nice thing about SQL: you describe what you want, not how to find it. You say “give me the names of companies in Dublin” and the database works out the steps.

Your first query

Press Run. This asks for two columns from the companies table.

Result: 12 rows
namecity
Brightwell AnalyticsDublin
Copperleaf FoodsCork
Harbourlight HealthGalway
Kettlebrook BankDublin
Pixelmoor GamesDublin
Quillstone MediaLondon
Glenvarra EnergyCork
Saltmarsh StoresLimerick
Larkspur FreightNULL
Umberfield SoftwareLondon
Willowby InsuranceGalway
Zillmere RoboticsBerlin
Read it like a sentence: “select the name and city columns, from the table called companies”. You get one result row for every company.
How the boxes work. Every grey box is a live editor. Change the query, press Run (or Ctrl+Enter, Cmd+Enter on a Mac) and your result replaces the expected one. Reset puts the original query back. Each run starts from a fresh copy of the practice data, so you cannot break anything. The first Run loads a small SQL engine, which takes a second.

2 The practice data

Made-up data for practice. The companies, numbers and dates below are invented. Any likeness to a real business is a coincidence.

There are three tables. The database is SQLite, a small free database that runs inside this page.

companies: one row per company

companies: 12 rows
company_idnameindustrycitysize_band
1Brightwell AnalyticsTechDublinMedium
2Copperleaf FoodsRetailCorkLarge
3Harbourlight HealthHealthGalwayLarge
4Kettlebrook BankFinanceDublinLarge
5Pixelmoor GamesTechDublinSmall
6Quillstone MediaMediaLondonSmall
7Glenvarra EnergyEnergyCorkMedium
8Saltmarsh StoresRetailLimerickMedium
9Larkspur FreightLogisticsNULLMedium
10Umberfield SoftwareTechLondonLarge
11Willowby InsuranceFinanceGalwaySmall
12Zillmere RoboticsTechBerlinSmall

offers: one row per job offer

offers: 45 rows
offer_idcompany_idjob_familylevelbase_salaryoffered_ataccepted_atstatus
14SalesJunior330002023-01-052023-01-13accepted
211DataJunior370002023-01-122023-01-25accepted
310ProductMid610002023-01-16NULLpending
46ProductMid535002023-01-312023-02-13accepted
52DataSenior740002023-02-062023-02-10accepted
68DataJunior415002023-02-232023-03-07accepted
79DesignJuniorNULL2023-03-122023-03-20accepted
83DesignMid485002023-03-152023-03-26accepted
98SalesMid425002023-03-172023-03-21accepted
106ProductSenior735002023-03-182023-03-28accepted
1111ProductJunior400002023-03-21NULLdeclined
125ProductMid535002023-03-27NULLdeclined
1311DesignMid435002023-04-172023-04-26accepted
149ProductMid585002023-05-152023-05-18accepted
1510EngineeringMid690002023-07-212023-07-28accepted
169DesignMid485002023-07-23NULLdeclined
1711ProductJunior395002023-07-25NULLdeclined
182ProductJunior480002023-07-272023-08-09accepted
192ProductJunior480002023-07-272023-08-09accepted
201DesignJunior380002023-08-032023-08-11accepted
219ProductMid575002023-09-052023-09-16accepted
228DataJunior385002023-09-132023-09-16accepted
239ProductSenior850002023-09-13NULLdeclined
248ProductJunior445002023-09-212023-10-01accepted
255DataSenior645002023-09-222023-10-02accepted
262DataSenior830002023-12-052023-12-17accepted
274SalesJunior315002024-01-02NULLdeclined
287DataMid545002024-01-312024-02-01accepted
298DesignSenior640002024-01-312024-02-03accepted
302EngineeringMid635002024-02-092024-02-13accepted
313SalesJunior340002024-03-272024-03-31accepted
321DesignJunior365002024-04-032024-04-15accepted
339ProductJunior410002024-04-082024-04-20accepted
345SalesJunior295002024-05-072024-05-19accepted
353DataJunior430002024-05-082024-05-13accepted
363DataMid570002024-05-122024-05-13accepted
3710DesignSenior680002024-05-262024-06-05accepted
388SalesMid420002024-07-082024-07-21accepted
393DataJunior450002024-08-292024-08-30accepted
404EngineeringJunior520002024-09-082024-09-10accepted
411DesignSenior685002024-09-222024-10-02accepted
427EngineeringJunior440002024-09-292024-10-09accepted
4310DesignSenior740002024-12-082024-12-11accepted
448DataSenior750002024-12-212024-12-27accepted
4510ProductSenior920002024-12-292025-01-03accepted

employees: one row per person who works at a company

employees: 30 rows
employee_idcompany_idjob_familylevelstart_date
11DataJunior2019-06-19
22ProductMid2022-06-19
32SalesJunior2020-07-10
42DesignMid2019-04-12
53ProductJunior2020-07-31
63DataSenior2020-04-17
74DesignJunior2023-02-19
84DataMid2021-03-27
95DesignJunior2019-02-14
105DesignMid2019-05-29
116EngineeringJunior2022-11-17
126SalesMid2024-11-01
136SalesMid2020-10-14
147DesignSenior2021-07-06
157DataMid2023-05-09
167EngineeringMid2021-03-17
178DataMid2024-08-20
188ProductMid2021-04-19
198DataMid2020-05-20
208EngineeringJunior2023-05-18
218DataSenior2022-08-05
229ProductSenior2019-03-06
239ProductMid2019-06-02
2410DesignMid2023-09-23
2510ProductMid2019-04-27
2611EngineeringSenior2019-09-20
2711DesignSenior2020-12-09
2811SalesMid2020-07-29
2912DesignJunior2024-10-16
3012SalesSenior2023-12-08

Traps hidden on purpose

Real data is messy, so this data is too. These come up again later:

Sandbox

A free editor. Try anything here, now or later.

Result: 5 rows
employee_idcompany_idjob_familylevelstart_date
178DataMid2024-08-20
188ProductMid2021-04-19
198DataMid2020-05-20
208EngineeringJunior2023-05-18
218DataSenior2022-08-05

3 SELECT and FROM

Every query you write starts from two words:

A few rules that apply to everything on this page:

Pick columns, or take them all

Result: 12 rows
nameindustry
Brightwell AnalyticsTech
Copperleaf FoodsRetail
Harbourlight HealthHealth
Kettlebrook BankFinance
Pixelmoor GamesTech
Quillstone MediaMedia
Glenvarra EnergyEnergy
Saltmarsh StoresRetail
Larkspur FreightLogistics
Umberfield SoftwareTech
Willowby InsuranceFinance
Zillmere RoboticsTech
You get the columns in the order you listed them.
Result: 12 rows
company_idnameindustrycitysize_band
1Brightwell AnalyticsTechDublinMedium
2Copperleaf FoodsRetailCorkLarge
3Harbourlight HealthHealthGalwayLarge
4Kettlebrook BankFinanceDublinLarge
5Pixelmoor GamesTechDublinSmall
6Quillstone MediaMediaLondonSmall
7Glenvarra EnergyEnergyCorkMedium
8Saltmarsh StoresRetailLimerickMedium
9Larkspur FreightLogisticsNULLMedium
10Umberfield SoftwareTechLondonLarge
11Willowby InsuranceFinanceGalwaySmall
12Zillmere RoboticsTechBerlinSmall
* means “every column”. It is handy for a first look at a table. In real work, list the columns you need: the query is clearer, quicker on big tables and does not change when someone adds a column.

Calculations

You can do sums in the SELECT line. The database works it out for every row.

Result: 5 rows
offer_idbase_salarymonthlymonthly_exactmonthly_rounded
133000275027502750
23700030833083.33333333333353083.33
36100050835083.3333333333335083.33
45350044584458.3333333333334458.33
57400061666166.6666666666676166.67
Look at offer 2: 37000 / 12 gives 3083, not 3083.33. When both numbers are whole numbers (integers), SQLite and Postgres throw away the part after the decimal point. Writing 12.0 makes it a decimal sum. ROUND(x, 2) rounds to two decimal places. Offer 7 shows NULL in every new column, because there is no salary to divide.

Aliases: new names

An alias is a nickname. AS monthly above gave the new column a name. You can also rename a table inside a query, which saves typing once queries use more than one table.

Result: 12 rows
companyhome city
Brightwell AnalyticsDublin
Copperleaf FoodsCork
Harbourlight HealthGalway
Kettlebrook BankDublin
Pixelmoor GamesDublin
Quillstone MediaLondon
Glenvarra EnergyCork
Saltmarsh StoresLimerick
Larkspur FreightNULL
Umberfield SoftwareLondon
Willowby InsuranceGalway
Zillmere RoboticsBerlin
c.name means “the name column from the table nicknamed c”. Single quotes are for text values; double quotes are for names of columns. Keep names simple (home_city) and you will rarely need double quotes at all.

Common mistakes

  • A missing comma: SELECT name industry does not fail. It quietly shows name under the heading industry, because SQL reads it as an alias.
  • A comma after the last column: SELECT name, city, FROM companies is an error.
  • Using double quotes for text. WHERE city = "Dublin" happens to work in SQLite but fails in Postgres. Use 'Dublin'.
  • Whole-number division. 5 / 2 is 2. Use 5 / 2.0 or 5 * 1.0 / 2.

Try it yourself

Exercise 3.1. Show each company's name and size band.

Hint: Two column names after SELECT, one table after FROM.

Show the answer
Result: 12 rows
namesize_band
Brightwell AnalyticsMedium
Copperleaf FoodsLarge
Harbourlight HealthLarge
Kettlebrook BankLarge
Pixelmoor GamesSmall
Quillstone MediaSmall
Glenvarra EnergyMedium
Saltmarsh StoresMedium
Larkspur FreightMedium
Umberfield SoftwareLarge
Willowby InsuranceSmall
Zillmere RoboticsSmall

Columns come back in the order you list them.

Exercise 3.2. For every offer, show the offer ID, the job family, the base salary and the weekly pay (salary divided by 52) rounded to 2 decimal places. Call the new column weekly_pay.

Hint: Divide by 52.0, not 52, then wrap it in ROUND( , 2).

Show the answer
Result: 45 rows
offer_idjob_familybase_salaryweekly_pay
1Sales33000634.62
2Data37000711.54
3Product610001173.08
4Product535001028.85
5Data740001423.08
6Data41500798.08
7DesignNULLNULL
8Design48500932.69
9Sales42500817.31
10Product735001413.46
11Product40000769.23
12Product535001028.85
13Design43500836.54
14Product585001125
15Engineering690001326.92
16Design48500932.69
17Product39500759.62
18Product48000923.08
19Product48000923.08
20Design38000730.77
21Product575001105.77
22Data38500740.38
23Product850001634.62
24Product44500855.77
25Data645001240.38
26Data830001596.15
27Sales31500605.77
28Data545001048.08
29Design640001230.77
30Engineering635001221.15
31Sales34000653.85
32Design36500701.92
33Product41000788.46
34Sales29500567.31
35Data43000826.92
36Data570001096.15
37Design680001307.69
38Sales42000807.69
39Data45000865.38
40Engineering520001000
41Design685001317.31
42Engineering44000846.15
43Design740001423.08
44Data750001442.31
45Product920001769.23

Using 52.0 keeps the pence. Offer 7 has a NULL salary, so its weekly pay is NULL too.

Exercise 3.3. Show company names under the heading company and industries under sector, using a table alias co.

Hint: FROM companies AS co, then co.name AS company.

Show the answer
Result: 12 rows
companysector
Brightwell AnalyticsTech
Copperleaf FoodsRetail
Harbourlight HealthHealth
Kettlebrook BankFinance
Pixelmoor GamesTech
Quillstone MediaMedia
Glenvarra EnergyEnergy
Saltmarsh StoresRetail
Larkspur FreightLogistics
Umberfield SoftwareTech
Willowby InsuranceFinance
Zillmere RoboticsTech

The alias only lasts for this one query. The real table keeps its name.

4 WHERE: keeping only some rows

WHERE is a filter. It comes after FROM. The database checks the condition on every row and keeps the rows where it is true.

Result: 3 rows
namecity
Brightwell AnalyticsDublin
Kettlebrook BankDublin
Pixelmoor GamesDublin
Three companies are in Dublin. Text comparisons with = are exact: 'dublin' in lower case finds nothing.

The comparison signs

Result: 10 rows
offer_idjob_familybase_salary
6Data41500
9Sales42500
11Product40000
13Design43500
24Product44500
33Product41000
35Data43000
38Sales42000
39Data45000
42Engineering44000
Offer 39, at exactly 45000, is included: BETWEEN includes both ends.
Result: 1 row
offer_idjob_familystatus
27Salesdeclined
IN is a short way of writing job_family = 'Engineering' OR job_family = 'Sales'.
Result: 9 rows
name
Brightwell Analytics
Copperleaf Foods
Pixelmoor Games
Quillstone Media
Saltmarsh Stores
Larkspur Freight
Umberfield Software
Willowby Insurance
Zillmere Robotics
In SQLite, LIKE ignores upper and lower case for English letters, so this also finds names starting with S. In Postgres, LIKE cares about case; use ILIKE to ignore it.

AND, OR and brackets

AND needs both conditions to be true. OR needs at least one. When you mix them, SQL does every AND first, the same way maths does × before +. Brackets change that order.

Result: 15 rows
offer_idjob_familybase_salary
2Data37000
3Product61000
5Data74000
6Data41500
10Product73500
22Data38500
23Product85000
25Data64500
26Data83000
28Data54500
35Data43000
36Data57000
39Data45000
44Data75000
45Product92000
Every Data offer appears, even the cheap ones, because the salary rule only stuck to Product.
Result: 8 rows
offer_idjob_familybase_salary
3Product61000
5Data74000
10Product73500
23Product85000
25Data64500
26Data83000
44Data75000
45Product92000
Now the salary rule applies to both families. When a query mixes AND and OR, add brackets every time, even when you think you don't need them.

Common mistakes

  • Forgetting quotes around text: WHERE city = Dublin makes SQL look for a column called Dublin.
  • Mixing AND and OR without brackets.
  • Forgetting the %: LIKE 'Bank' only matches the exact word Bank.
  • Expecting BETWEEN to leave out the end values. It includes them.

Try it yourself

Exercise 4.1. List the names of all Tech companies.

Hint: WHERE industry = 'Tech'. Mind the capital T.

Show the answer
Result: 4 rows
name
Brightwell Analytics
Pixelmoor Games
Umberfield Software
Zillmere Robotics

Four companies. Text must match exactly, including capitals.

Exercise 4.2. Find accepted offers for Senior roles paying at least 70000. Show offer ID, job family and salary.

Hint: Three conditions joined with AND. “At least” is >=.

Show the answer
Result: 6 rows
offer_idjob_familybase_salary
5Data74000
10Product73500
26Data83000
43Design74000
44Data75000
45Product92000

Offer 23 pays 85000 but was declined, so it is left out.

Exercise 4.3. Find companies that are in Cork or Galway, or whose name ends in “Bank”.

Hint: Use IN for the cities, LIKE '%Bank' for the name, joined by OR.

Show the answer
Result: 5 rows
namecity
Copperleaf FoodsCork
Harbourlight HealthGalway
Kettlebrook BankDublin
Glenvarra EnergyCork
Willowby InsuranceGalway

With only ORs there is no order problem, so brackets are optional here.

5 NULL: when a value is missing

NULL means “no value here” or “unknown”. It is not zero and it is not empty text. Larkspur Freight's city is NULL: the city exists, nobody recorded it.

Here is the part that catches everyone. Any comparison with an unknown value gives an unknown answer. Is the unknown city equal to Dublin? Unknown. Is it not equal to Dublin? Also unknown. WHERE only keeps rows where the answer is a clear yes, so rows with NULL quietly drop out.

Result: 0 rows
namecity
No rows
No rows. “Is this value equal to unknown?” is never a clear yes, not even for the row that is NULL.
Result: 1 row
namecity
Larkspur FreightNULL
Use IS NULL and IS NOT NULL. They are the only tests that give a clear yes or no for missing values.
Result: 8 rows
namecity
Copperleaf FoodsCork
Harbourlight HealthGalway
Quillstone MediaLondon
Glenvarra EnergyCork
Saltmarsh StoresLimerick
Umberfield SoftwareLondon
Willowby InsuranceGalway
Zillmere RoboticsBerlin
Count the rows: Larkspur Freight is missing, even though it is not in Dublin. If you want it, add OR city IS NULL.

Replacing NULL with something readable

Result: 12 rows
namecity
Brightwell AnalyticsDublin
Copperleaf FoodsCork
Harbourlight HealthGalway
Kettlebrook BankDublin
Pixelmoor GamesDublin
Quillstone MediaLondon
Glenvarra EnergyCork
Saltmarsh StoresLimerick
Larkspur FreightNot recorded
Umberfield SoftwareLondon
Willowby InsuranceGalway
Zillmere RoboticsBerlin
COALESCE(a, b) gives back a unless it is NULL, in which case it gives b. Also: maths with NULL gives NULL. NULL + 5 is NULL.

Common mistakes

  • Writing = NULL or <> NULL. Always IS NULL / IS NOT NULL.
  • Forgetting that <> drops NULL rows.
  • Treating NULL as zero. A missing salary is not a salary of 0. Replacing it with 0 would drag an average down.

Try it yourself

Exercise 5.1. List every offer that has not been accepted (no acceptance date). Show offer ID, status and accepted_at.

Hint: accepted_at IS NULL.

Show the answer
Result: 7 rows
offer_idstatusaccepted_at
3pendingNULL
11declinedNULL
12declinedNULL
16declinedNULL
17declinedNULL
23declinedNULL
27declinedNULL

These are the declined and pending offers.

Exercise 5.2. Find any offer where the salary is missing.

Hint: base_salary IS NULL.

Show the answer
Result: 1 row
offer_idcompany_idjob_familylevelbase_salaryoffered_ataccepted_atstatus
79DesignJuniorNULL2023-03-122023-03-20accepted

Just offer 7. Worth knowing before you average salaries.

Exercise 5.3. List companies that are not in Dublin, and make sure Larkspur Freight is included.

Hint: city <> 'Dublin' OR city IS NULL.

Show the answer
Result: 9 rows
namecity
Copperleaf FoodsCork
Harbourlight HealthGalway
Quillstone MediaLondon
Glenvarra EnergyCork
Saltmarsh StoresLimerick
Larkspur FreightNULL
Umberfield SoftwareLondon
Willowby InsuranceGalway
Zillmere RoboticsBerlin

Without the second line, the company with no city vanishes.

6 ORDER BY and LIMIT

A table has no built-in order. Unless you ask, rows come back in whatever order is easiest for the database. ORDER BY sorts them. LIMIT keeps the first few.

Result: 5 rows
offer_idjob_familybase_salary
45Product92000
23Product85000
26Data83000
44Data75000
5Data74000
This “sort, then take the top few” pattern is everywhere: top 5 products, 10 most recent orders.
Result: 10 rows
offer_idjob_familylevelbase_salary
15EngineeringMid69000
30EngineeringMid63500
40EngineeringJunior52000
42EngineeringJunior44000
9SalesMid42500
38SalesMid42000
31SalesJunior34000
1SalesJunior33000
27SalesJunior31500
34SalesJunior29500
Engineering comes before Sales because E comes before S. Within each family, salaries run high to low.
The parts of a query always go in this order: SELECT → FROM → WHERE → ORDER BY → LIMIT. Putting them in the wrong order is an error.
Other databases: SQL Server uses SELECT TOP 5 ... instead of LIMIT 5. SQLite and Postgres put NULLs first when sorting smallest-first; Snowflake and Oracle put them last. You can say which you want with NULLS LAST in most databases.

Common mistakes

  • Using LIMIT without ORDER BY and expecting “the top 5”. You get any 5.
  • Forgetting that NULL sorts first in SQLite when you sort smallest-first. Run the lowest-salary query below without a filter and offer 7 comes out on top.
  • Ties: if the 5th and 6th rows have the same salary, LIMIT 5 cuts one at random.

Try it yourself

Exercise 6.1. Show the three lowest-paid accepted offers.

Hint: Filter on status, sort ascending, LIMIT 3. Filter out the NULL salary too.

Show the answer
Result: 3 rows
offer_idjob_familybase_salary
34Sales29500
1Sales33000
31Sales34000

Without IS NOT NULL, offer 7 (no salary) would sort first.

Exercise 6.2. List companies sorted by city, then by name within each city.

Hint: Two columns after ORDER BY.

Show the answer
Result: 12 rows
cityname
NULLLarkspur Freight
BerlinZillmere Robotics
CorkCopperleaf Foods
CorkGlenvarra Energy
DublinBrightwell Analytics
DublinKettlebrook Bank
DublinPixelmoor Games
GalwayHarbourlight Health
GalwayWillowby Insurance
LimerickSaltmarsh Stores
LondonQuillstone Media
LondonUmberfield Software

The NULL city sorts to the top.

Exercise 6.3. Show the 5 most recent offers by the date they were made.

Hint: Dates written YYYY-MM-DD sort correctly. DESC for newest first.

Show the answer
Result: 5 rows
offer_idoffered_atstatus
452024-12-29accepted
442024-12-21accepted
432024-12-08accepted
422024-09-29accepted
412024-09-22accepted

Dates stored as year-month-day text sort in date order. Section 14 explains why.

7 DISTINCT: removing repeats

SELECT DISTINCT removes duplicate rows from the result. Use it to answer “which different values are there?”.

Result: 7 rows
industry
Energy
Finance
Health
Logistics
Media
Retail
Tech
Twelve companies, seven different industries.
Result: 11 rows
industrysize_band
EnergyMedium
FinanceLarge
FinanceSmall
HealthLarge
LogisticsMedium
MediaSmall
RetailLarge
RetailMedium
TechLarge
TechMedium
TechSmall
With two columns, DISTINCT looks at the pair. Tech appears three times because Tech-Large, Tech-Medium and Tech-Small are different pairs.

Common mistakes

  • Thinking DISTINCT applies to one column. It applies to the whole result row.
  • Adding DISTINCT to make a strange result look tidy. If you see repeated rows you did not expect, find out why first (often a join, section 13).

Try it yourself

Exercise 7.1. Which job families have had offers? Show each once.

Hint: SELECT DISTINCT job_family.

Show the answer
Result: 5 rows
job_family
Data
Design
Engineering
Product
Sales

Five families.

Exercise 7.2. Which cities do the companies sit in? Include the missing one.

Hint: DISTINCT keeps NULL as one of the values.

Show the answer
Result: 7 rows
city
NULL
Berlin
Cork
Dublin
Galway
Limerick
London

NULL appears once. DISTINCT treats all NULLs as the same.

8 Counting and adding up: COUNT, SUM, AVG, MIN, MAX

So far every result row matched a row in the table. Aggregate functions squash many rows into one number.

Result: 1 row
all_offerswith_salarycompanieslowesthighestaverage
454411295009200053159
45 rows, but 44 with a salary: COUNT(base_salary) skips offer 7. AVG also skips it, so the average is over 44 salaries. That is usually what you want; just know it is happening.
Result: 1 row
acceptedtotal_pay
381980000
WHERE runs first, so only accepted offers are counted and added.

Common mistakes

  • Using COUNT(column) when you meant every row. NULLs are skipped.
  • Thinking AVG treats NULL as 0. It leaves those rows out.
  • Mixing a plain column with an aggregate: SELECT job_family, COUNT(*) FROM offers. Most databases give an error. SQLite runs it and shows one job family picked at random, which is worse. Section 9 is the fix.

Try it yourself

Exercise 8.1. How many offers were accepted?

Hint: COUNT(*) with a WHERE.

Show the answer
Result: 1 row
accepted
38

38 of the 45.

Exercise 8.2. What are the lowest and highest salaries offered for Data roles?

Hint: MIN and MAX with WHERE job_family = 'Data'.

Show the answer
Result: 1 row
lowesthighest
3700083000

Two aggregates, one row.

Exercise 8.3. How many different companies have made at least one offer?

Hint: COUNT(DISTINCT company_id) on the offers table.

Show the answer
Result: 1 row
companies_with_offers
11

11, not 12: Zillmere Robotics has made none.

9 GROUP BY: one answer per group

GROUP BY lets you count or average per something: per job family, per company, per year. Picture what happens with the 7 offers from Saltmarsh Stores (company 8):

Before: 7 rows

rows: 7 rows
offer_idjob_familybase_salary
6Data41500
22Data38500
44Data75000
29Design64000
24Product44500
9Sales42500
38Sales42000

After GROUP BY job_family: 4 rows

groups: 4 rows
job_familyofferstotal
Data3155000
Design164000
Product144500
Sales284500
  1. The database sorts the rows into piles, one pile per job family: 3 Data rows, 1 Design, 1 Product, 2 Sales.
  2. Each pile becomes one row in the result.
  3. Aggregates such as COUNT(*) and SUM are worked out inside each pile.

The golden rule: every column in SELECT must either be in the GROUP BY or be inside an aggregate. A pile has one job family, so you can show it. A pile has three salaries, so you must say how to combine them (sum, average, max...).

Result: 5 rows
job_familyoffers
Product14
Data11
Design10
Sales6
Engineering4
One row per job family. ORDER BY offers can use the alias from the SELECT line.
Result: 13 rows
job_familyleveloffersavg_salary
DataJunior541000
DataMid255750
DataSenior474125
DesignJunior337250
DesignMid346833
DesignSenior468625
EngineeringJunior248000
EngineeringMid266250
ProductJunior643500
ProductMid556800
ProductSenior383500
SalesJunior432000
SalesMid242250
Two columns in GROUP BY means one pile per combination. Combinations with no rows (Engineering-Senior) do not appear at all.

Common mistakes

  • A column in SELECT that is not in GROUP BY and not inside an aggregate.
  • Forgetting that groups with no rows are simply missing, not shown as zero.
  • Grouping by a column you are not showing. Legal, but the result looks like it has duplicates.

Try it yourself

Exercise 9.1. How many offers are there for each status?

Hint: GROUP BY status.

Show the answer
Result: 3 rows
statusoffers
accepted38
declined6
pending1

Accepted, declined, pending.

Exercise 9.2. How many companies are there in each industry? Biggest first.

Hint: GROUP BY industry on companies, ORDER BY the count DESC.

Show the answer
Result: 7 rows
industrycompanies
Tech4
Finance2
Retail2
Energy1
Health1
Logistics1
Media1

The second sort column breaks ties alphabetically, so the order is always the same.

Exercise 9.3. What is the average accepted salary at each level, rounded to a whole number, highest first?

Hint: WHERE status = 'accepted', then GROUP BY level.

Show the answer
Result: 3 rows
levelavg_salary
Senior73650
Mid53636
Junior40844

WHERE filters rows before they go into the piles.

10 HAVING vs WHERE

Both are filters. The difference is when they run.

The database works through a query in this order, which is not the order you write it:

FROM (get the table) → WHERE (drop rows) → GROUP BY (make piles) → HAVING (drop piles) → SELECT (pick columns) → ORDER BY (sort) → LIMIT (cut).

Result
Error: misuse of aggregate: COUNT()
An error. At the WHERE step there are no groups, so there is nothing to count.
Result: 4 rows
job_familyoffers
Data11
Design10
Product14
Sales6
Engineering, with 4 offers, is dropped.
Result: 4 rows
job_familyacceptedavg_salary
Data1155727
Design955125
Engineering457125
Product957389
Both in one query. Only accepted offers make it into the piles; then only piles with a high average survive.

Common mistakes

  • Putting an aggregate in WHERE.
  • Putting a plain row filter in HAVING. It may work, but it is slower and harder to read. Filter rows with WHERE.

Try it yourself

Exercise 10.1. Which companies (by company_id) have made at least 5 offers?

Hint: GROUP BY company_id, HAVING COUNT(*) >= 5.

Show the answer
Result: 5 rows
company_idoffers
87
96
105
35
25

Section 12 shows how to bring in the names.

Exercise 10.2. Which levels have an average accepted salary above 50000?

Hint: WHERE for accepted, HAVING for the average.

Show the answer
Result: 2 rows
levelavg_salary
Mid53636
Senior73650

Mid and Senior. Junior averages below 50000.

11 CASE WHEN: if this, then that

CASE lets you write rules that give a different value depending on the row. It reads like plain English:

Result: 12 rows
offer_idbase_salarypay_band
4592000High
2385000High
2683000High
4475000High
574000High
4374000High
1073500High
1569000Middle
4168500Middle
3768000Middle
2564500Middle
2964000Middle
The database checks each WHEN from the top and stops at the first one that is true. That is why 85000 is High and not Middle, even though it is also over 45000. ELSE catches everything else. END closes it.

A very common use: counting only some rows inside a GROUP BY. Give 1 to the rows you want and 0 to the rest, then add them up.

Result: 5 rows
job_familyoffersacceptedaccept_pct
Engineering44100
Data1111100
Design10990
Sales6583.3
Product14964.3
The 100.0 matters: without the decimal point, the division would be done in whole numbers and most percentages would come out as 0.

Common mistakes

  • No ELSE. Rows that match no WHEN get NULL.
  • WHENs in the wrong order. Put the narrowest rule first.
  • A NULL value matches none of WHEN x > 5 or WHEN x <= 5. Add WHEN x IS NULL first if you care about it.
  • Forgetting END.

Try it yourself

Exercise 11.1. Label each company “Ireland” if its city is Dublin, Cork, Galway or Limerick, “Unknown” if the city is missing, and “Abroad” otherwise.

Hint: Check IS NULL first, then IN (...).

Show the answer
Result: 12 rows
namecitylocation
Brightwell AnalyticsDublinIreland
Copperleaf FoodsCorkIreland
Harbourlight HealthGalwayIreland
Kettlebrook BankDublinIreland
Pixelmoor GamesDublinIreland
Quillstone MediaLondonAbroad
Glenvarra EnergyCorkIreland
Saltmarsh StoresLimerickIreland
Larkspur FreightNULLUnknown
Umberfield SoftwareLondonAbroad
Willowby InsuranceGalwayIreland
Zillmere RoboticsBerlinAbroad

If the NULL test came last, Larkspur would fall into ELSE and be labelled Abroad.

Exercise 11.2. For each job family, show the number of accepted offers and declined offers as two columns.

Hint: Two SUM(CASE WHEN ... THEN 1 ELSE 0 END) columns.

Show the answer
Result: 5 rows
job_familyaccepteddeclined
Data110
Design91
Engineering40
Product94
Sales51

This turns rows into columns, which people call a pivot.

12 JOINs: combining tables

The offers table knows a company's ID but not its name. The name lives in companies. A join puts matching rows from two tables side by side, so you can see both.

You tell the join how rows match with ON. Here: an offer matches a company when their company_id values are the same.

companiesoffers 5 · Pixelmoor 6 · Quillstone 12 · Zillmere offer 12 · co. 5 offer 25 · co. 5 offer 4 · co. 6 offer 10 · co. 6
Rows match on company_id. Pixelmoor has two offers, so it appears in two result rows. Zillmere has no line, because no offer has company_id 12: an INNER JOIN drops it, a LEFT JOIN keeps it with NULLs.

INNER JOIN: only rows that match

Result: 5 rows
company_idnameoffer_idjob_family
5Pixelmoor Games12Product
5Pixelmoor Games25Data
5Pixelmoor Games34Sales
6Quillstone Media4Product
6Quillstone Media10Product
Four rows. A company with two offers shows up twice, once per offer. Zillmere Robotics is gone, because no offer matched it. Plain JOIN means the same as INNER JOIN.

LEFT JOIN: keep everything on the left

Result: 6 rows
company_idnameoffer_idjob_family
5Pixelmoor Games12Product
5Pixelmoor Games25Data
5Pixelmoor Games34Sales
6Quillstone Media4Product
6Quillstone Media10Product
12Zillmere RoboticsNULLNULL
Five rows. The “left” table is the one named first (companies). Every company stays. Where nothing matched, the offer columns are filled with NULL.

That NULL is useful. To find rows with no match, LEFT JOIN and keep the rows where the right side is NULL:

Result: 1 row
name
Zillmere Robotics
This “anti-join” pattern answers questions like “which customers never ordered?”.

A trap: filtering the right-hand table

Result: 4 rows
nameoffer_id
Quillstone Media4
Quillstone Media10
Pixelmoor Games25
Pixelmoor Games34
Zillmere vanished again. Its offer columns are NULL, and NULL = 'accepted' is not true, so WHERE threw it out. The LEFT JOIN has quietly become an INNER JOIN.
Result: 5 rows
nameoffer_id
Pixelmoor Games25
Pixelmoor Games34
Quillstone Media4
Quillstone Media10
Zillmere RoboticsNULL
Conditions on the right-hand table go in ON. Now only accepted offers are matched, and every company is kept.
Other databases: RIGHT JOIN keeps everything on the right instead; most people just swap the tables and use LEFT. FULL OUTER JOIN keeps unmatched rows from both sides. Older versions of SQLite support neither, so this page sticks to INNER and LEFT.

Common mistakes

  • Joining on the wrong column, such as o.offer_id = c.company_id. It runs and gives nonsense.
  • Filtering the right-hand table in WHERE after a LEFT JOIN.
  • Using COUNT(*) after a LEFT JOIN. A company with no offers still has one row, so it counts as 1. Use COUNT(o.offer_id).

Try it yourself

Exercise 12.1. List every accepted offer with the company name and city.

Hint: JOIN offers to companies ON company_id, WHERE status = 'accepted'.

Show the answer
Result: 38 rows
offer_idnamecityjob_familybase_salary
1Kettlebrook BankDublinSales33000
2Willowby InsuranceGalwayData37000
4Quillstone MediaLondonProduct53500
5Copperleaf FoodsCorkData74000
6Saltmarsh StoresLimerickData41500
7Larkspur FreightNULLDesignNULL
8Harbourlight HealthGalwayDesign48500
9Saltmarsh StoresLimerickSales42500
10Quillstone MediaLondonProduct73500
13Willowby InsuranceGalwayDesign43500
14Larkspur FreightNULLProduct58500
15Umberfield SoftwareLondonEngineering69000
18Copperleaf FoodsCorkProduct48000
19Copperleaf FoodsCorkProduct48000
20Brightwell AnalyticsDublinDesign38000
21Larkspur FreightNULLProduct57500
22Saltmarsh StoresLimerickData38500
24Saltmarsh StoresLimerickProduct44500
25Pixelmoor GamesDublinData64500
26Copperleaf FoodsCorkData83000
28Glenvarra EnergyCorkData54500
29Saltmarsh StoresLimerickDesign64000
30Copperleaf FoodsCorkEngineering63500
31Harbourlight HealthGalwaySales34000
32Brightwell AnalyticsDublinDesign36500
33Larkspur FreightNULLProduct41000
34Pixelmoor GamesDublinSales29500
35Harbourlight HealthGalwayData43000
36Harbourlight HealthGalwayData57000
37Umberfield SoftwareLondonDesign68000
38Saltmarsh StoresLimerickSales42000
39Harbourlight HealthGalwayData45000
40Kettlebrook BankDublinEngineering52000
41Brightwell AnalyticsDublinDesign68500
42Glenvarra EnergyCorkEngineering44000
43Umberfield SoftwareLondonDesign74000
44Saltmarsh StoresLimerickData75000
45Umberfield SoftwareLondonProduct92000

One row per accepted offer, now with names.

Exercise 12.2. How many offers has each industry made?

Hint: Join, then GROUP BY c.industry.

Show the answer
Result: 7 rows
industryoffers
Retail12
Tech11
Finance7
Logistics6
Health5
Media2
Energy2

Industry lives in companies, the count comes from offers, so you need both.

Exercise 12.3. Show every company with its number of offers, including companies with none.

Hint: LEFT JOIN, and COUNT(o.offer_id) rather than COUNT(*).

Show the answer
Result: 12 rows
nameoffers
Saltmarsh Stores7
Larkspur Freight6
Copperleaf Foods5
Harbourlight Health5
Umberfield Software5
Willowby Insurance4
Brightwell Analytics3
Kettlebrook Bank3
Pixelmoor Games3
Glenvarra Energy2
Quillstone Media2
Zillmere Robotics0

Zillmere Robotics shows 0. With COUNT(*) it would wrongly show 1.

13 Grain: what one row means

The grain of a table is the answer to “what does one row stand for?”. Say it out loud before you write any query.

Joins can change the grain. Join companies to offers and the result is one row per offer, not per company. That is fine when you expect it. It goes wrong when you join two tables that are both “many per company”.

How joins duplicate rows

Saltmarsh Stores (company 8) has 7 offers and 5 employees. Join both to the company and every offer pairs with every employee: 7 × 5 = 35 rows.

Result: 1 row
nameoffersemployeestotal_offer_pay
Saltmarsh Stores35351740000
Both counts say 35. The pay total is five times too big, because each offer was counted once per employee. Nothing errors. The number just looks plausible and is wrong. This is one of the most common mistakes in real work.
Result: 1 row
nameoffersemployees
Saltmarsh Stores75
COUNT(DISTINCT ...) rescues counts, but there is no such rescue for sums. The real fix is to bring each table down to the company grain first, then join. Section 15 does exactly that.

Checking a grain

If a table is meant to be one row per offer, the offer ID should never repeat. Compare the row count with the count of distinct IDs:

Result: 1 row
row_countdistinct_ids
4545
Equal, so each offer ID appears once. But that does not prove each real offer appears once. See the exercise below.

Common mistakes

  • Joining two “many” tables to the same key and then adding things up.
  • Using DISTINCT to hide a duplicate problem rather than finding where it comes from.
  • Not writing down the grain of each step. One comment line (-- one row per company) prevents most of these bugs.

Try it yourself

Exercise 13.1. Find offers that look like duplicates: identical in every column except offer_id.

Hint: GROUP BY every other column, HAVING COUNT(*) > 1.

Show the answer
Result: 1 row
company_idjob_familylevelbase_salaryoffered_ataccepted_atstatuscopies
2ProductJunior480002023-07-272023-08-09accepted2

Offers 18 and 19. Whether they are real is a question for whoever owns the data. Finding them is your job.

Exercise 13.2. Check the grain of employees: is employee_id unique?

Hint: Compare COUNT(*) with COUNT(DISTINCT employee_id).

Show the answer
Result: 1 row
row_countdistinct_ids
3030

Both 30, so yes.

14 Working with dates

SQLite has no special date type. Dates here are stored as text in the form YYYY-MM-DD, such as '2024-05-12'. Because the year comes first, sorting and comparing the text gives the right date order. '2023-12-31' < '2024-01-01' is true.

Pulling out the year, month or quarter

strftime(format, date) pulls pieces out of a date. '%Y' is the year, '%m' the month, '%Y-%m' year and month together. SQLite has no quarter code, so we work it out from the month: months 1-3 are quarter 1, and so on.

Result: 6 rows
offer_idaccepted_atyearmonthquarter
12023-01-1320232023-011
22023-01-2520232023-011
42023-02-1320232023-021
52023-02-1020232023-021
62023-03-0720232023-031
72023-03-2020232023-031
CAST(x AS INTEGER) turns the text '05' into the number 5. Then (5 + 2) / 3 = 2 in whole-number division: May is in quarter 2.
Result: 9 rows
yearquarteraccepted_offers
202319
202322
202336
202343
202414
202426
202433
202444
202511
Counting per quarter. A quarter with no accepted offers would simply not appear. The lonely 2025 row is offer 45.

Days between two dates

Result: 5 rows
offer_idoffered_ataccepted_atdays_to_accept
22023-01-122023-01-2513
42023-01-312023-02-1313
182023-07-272023-08-0913
192023-07-272023-08-0913
382024-07-082024-07-2113
julianday turns a date into a day number, so subtracting two gives the days between them.

Filtering a date range

Result: 1 row
offers_made_in_2024
19
“From the first day, up to but not including the next year” is the safest pattern. It still works if the column ever holds times as well as dates.
Result: 1 row
rows_found
0
Zero. strftime returns the text '2024', and SQLite says text is never equal to the number 2024. Write = '2024' with quotes.
Other databases: Postgres, Snowflake and BigQuery have real date types. Use EXTRACT(YEAR FROM d), EXTRACT(QUARTER FROM d) or DATE_TRUNC('quarter', d) (BigQuery: DATE_TRUNC(d, QUARTER)). Days between dates: d2 - d1 in Postgres, DATEDIFF('day', d1, d2) in Snowflake, DATE_DIFF(d2, d1, DAY) in BigQuery.

Common mistakes

  • Comparing strftime's text result with a number.
  • BETWEEN '2024-01-01' AND '2024-12-31' on a column with times: anything after midnight on 31 December is lost.
  • Dates stored in another format, like 12/05/2024. They do not sort correctly as text. Fix the format first.

Try it yourself

Exercise 14.1. How many offers were made in 2023?

Hint: offered_at >= '2023-01-01' AND < '2024-01-01'.

Show the answer
Result: 1 row
offers_2023
26

A range on the raw column is also faster on big tables than a function on every row.

Exercise 14.2. Count accepted offers per month in 2024, shown as 2024-01, 2024-02 and so on.

Hint: GROUP BY strftime('%Y-%m', accepted_at), filter to 2024.

Show the answer
Result: 10 rows
monthaccepted
2024-023
2024-031
2024-042
2024-053
2024-061
2024-071
2024-081
2024-091
2024-102
2024-122

Months with no acceptances are missing rather than shown as 0.

Exercise 14.3. Which accepted offer was accepted fastest, and in how many days?

Hint: julianday difference, sort ascending, LIMIT 1.

Show the answer
Result: 1 row
offer_iddays_to_accept
281

Several offers were accepted the next day; sorting by offer_id too picks the same one every time.

15 CTEs: named steps, read top to bottom

Long queries get hard to read. A CTE (common table expression) lets you name a step and use it like a table further down. You write it with WITH:

Result: 11 rows
company_idaccepted_offersavg_salary
10475750
6263500
2563300
9452333
8749714
7249250
1347667
5247000
3545500
4242500
11240250
Read it like a recipe. Step 1 makes a temporary table called accepted. Step 2 uses it. The CTE only exists while this query runs.

You can chain several steps with commas. Each step can use the ones above it. Here is the proper fix for the grain problem from section 13: shrink offers and employees to one row per company before joining.

Result: 12 rows
nameoffersemployeestotal_offer_pay
Brightwell Analytics31143000
Copperleaf Foods53316500
Harbourlight Health52227500
Kettlebrook Bank32116500
Pixelmoor Games32147500
Quillstone Media23127000
Glenvarra Energy2398500
Saltmarsh Stores75348000
Larkspur Freight62290500
Umberfield Software52364000
Willowby Insurance43160000
Zillmere Robotics02NULL
Saltmarsh Stores now shows 7 offers, 5 employees and the true pay total. Every join here is one-row-to-one-row, so nothing can multiply.
Other databases: CTEs work the same way in Postgres, Snowflake, BigQuery, SQL Server and MySQL 8+. An older alternative is a subquery: a query inside brackets in the FROM line. CTEs do the same job and read better.

Common mistakes

  • A comma after the last CTE, before the final SELECT.
  • Forgetting the brackets around each step.
  • Naming steps t1, t2, t3. Name them for what they hold.

Try it yourself

Exercise 15.1. Using a CTE, find the overall average accepted salary, then list the accepted offers that are above it.

Hint: Step 1: one row holding the average. Then join it on with a JOIN that has no condition (CROSS JOIN), or put it in the WHERE.

Show the answer
Result: 16 rows
offer_idjob_familybase_salaryoverall_avg
45Product9200053514
26Data8300053514
44Data7500053514
5Data7400053514
43Design7400053514
10Product7350053514
15Engineering6900053514
41Design6850053514
37Design6800053514
25Data6450053514
29Design6400053514
30Engineering6350053514
14Product5850053514
21Product5750053514
36Data5700053514
28Data5450053514

A CROSS JOIN pairs every row with every row. With a one-row table, that just adds the average to each offer.

Exercise 15.2. How many companies have made 2 offers, how many 3, and so on?

Hint: Step 1: offers per company. Step 2: GROUP BY that count.

Show the answer
Result: 6 rows
offers_madecompanies
22
33
41
53
61
71

A group of groups. Without a CTE this needs a subquery, and is harder to read.

16 Window functions

This is the part people find hardest, so go slowly.

GROUP BY squashes each pile of rows into one row. A window function also looks at a pile of related rows, but it does not squash them. Every row stays, and gets a new value worked out from its pile. The pile is called the window.

You spot a window function by the word OVER. Inside the brackets:

Step 1: an average next to every row

Result: 10 rows
offer_idjob_familybase_salaryfamily_avg
15Engineering6900057125
30Engineering6350057125
40Engineering5200057125
42Engineering4400057125
9Sales4250035417
38Sales4200035417
31Sales3400035417
1Sales3300035417
27Sales3150035417
34Sales2950035417
Every offer is still here. Each one now carries the average of its own family, so you can compare it with its peers. With GROUP BY you would get two rows, and lose the offers.

Step 2: numbering rows: ROW_NUMBER, RANK, DENSE_RANK

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. ROW_NUMBER always counts 1, 2, 3... and breaks ties at random. RANK gives ties the same number, then skips the next number. DENSE_RANK gives ties the same number and does not skip.

Step 3: the top row in each group

Window functions cannot go in WHERE (they are worked out after it), so number the rows in a CTE, then filter:

Result: 5 rows
job_familyoffer_idbase_salary
Data2683000
Design4374000
Engineering1569000
Product4592000
Sales942500
“Highest-paid offer per family”, “latest order per customer”, “first login per user”: all the same pattern.

Step 4: looking back with LAG

LAG(x) gives the value of x from the row before, in the order you set. LEAD(x) looks forward. The first row has nothing before it, so it gets NULL.

Result: 9 rows
quarteracceptedprevious_quarterchange
2023-Q19NULLNULL
2023-Q229-7
2023-Q3624
2023-Q436-3
2024-Q1431
2024-Q2642
2024-Q336-3
2024-Q4431
2025-Q114-3
|| glues text together, making labels like 2024-Q2. Note that LAG looks at the previous row, not the previous quarter: if a quarter were missing, LAG would skip straight over it.

Step 5: running totals

Result: 10 rows
monthacceptedrunning_total
2024-0233
2024-0314
2024-0426
2024-0539
2024-06110
2024-07111
2024-08112
2024-09113
2024-10215
2024-12217
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW means “from the first row up to this one”. That is the frame: which rows in the window to add up. If you leave it out, rows that tie on the ORDER BY value are added together in one go, which surprises people.

Common mistakes

  • Putting a window function in WHERE. Wrap it in a CTE and filter outside.
  • Using ROW_NUMBER when ties matter. Use RANK or DENSE_RANK.
  • Forgetting PARTITION BY, so the numbering runs across the whole table instead of restarting per group.
  • Assuming LAG means “the previous month”. It means the previous row.

Try it yourself

Exercise 16.1. Number each company's offers in the order they were made (1 = first offer). Show company_id, offer_id, offered_at and the number.

Hint: ROW_NUMBER() OVER (PARTITION BY company_id ORDER BY offered_at).

Show the answer
Result: 45 rows
company_idoffer_idoffered_atnth_offer
1202023-08-031
1322024-04-032
1412024-09-223
252023-02-061
2182023-07-272
2192023-07-273
2262023-12-054
2302024-02-095
382023-03-151
3312024-03-272
3352024-05-083
3362024-05-124
3392024-08-295
412023-01-051
4272024-01-022
4402024-09-083
5122023-03-271
5252023-09-222
5342024-05-073
642023-01-311
6102023-03-182
7282024-01-311
7422024-09-292
862023-02-231
892023-03-172
8222023-09-133
8242023-09-214
8292024-01-315
8382024-07-086
8442024-12-217
972023-03-121
9142023-05-152
9162023-07-233
9212023-09-054
9232023-09-135
9332024-04-086
1032023-01-161
10152023-07-212
10372024-05-263
10432024-12-084
10452024-12-295
1122023-01-121
11112023-03-212
11132023-04-173
11172023-07-254

Adding offer_id to the ORDER BY settles the tie between offers 18 and 19, made on the same day.

Exercise 16.2. Find the second-highest salary in each job family.

Hint: DENSE_RANK in a CTE, then WHERE rnk = 2.

Show the answer
Result: 5 rows
job_familyoffer_idbase_salary
Data4475000
Design4168500
Engineering3063500
Product2385000
Sales3842000

DENSE_RANK means “second-highest value”, even if two offers tie for first.

Exercise 16.3. For each accepted offer, show how many days had passed since the same company's previous accepted offer.

Hint: LAG(accepted_at) partitioned by company, ordered by accepted_at, then julianday difference.

Show the answer
Result: 38 rows
company_idoffer_idaccepted_atprevious_acceptdays_since
1202023-08-11NULLNULL
1322024-04-152023-08-11248
1412024-10-022024-04-15170
252023-02-10NULLNULL
2182023-08-092023-02-10180
2192023-08-092023-08-090
2262023-12-172023-08-09130
2302024-02-132023-12-1758
382023-03-26NULLNULL
3312024-03-312023-03-26371
3352024-05-132024-03-3143
3362024-05-132024-05-130
3392024-08-302024-05-13109
412023-01-13NULLNULL
4402024-09-102023-01-13606
5252023-10-02NULLNULL
5342024-05-192023-10-02230
642023-02-13NULLNULL
6102023-03-282023-02-1343
7282024-02-01NULLNULL
7422024-10-092024-02-01251
862023-03-07NULLNULL
892023-03-212023-03-0714
8222023-09-162023-03-21179
8242023-10-012023-09-1615
8292024-02-032023-10-01125
8382024-07-212024-02-03169
8442024-12-272024-07-21159
972023-03-20NULLNULL
9142023-05-182023-03-2059
9212023-09-162023-05-18121
9332024-04-202023-09-16217
10152023-07-28NULLNULL
10372024-06-052023-07-28313
10432024-12-112024-06-05189
10452025-01-032024-12-1123
1122023-01-25NULLNULL
11132023-04-262023-01-2591

Each company's first accepted offer has no previous one, so it shows NULL.

17 Median and percentiles

The median is the middle value when you line all the values up in order. Half are below it, half above. With an even number of values, it is the average of the middle two.

Why bother when AVG exists? Because one huge value drags an average up but barely moves the median. Pay, house prices and response times usually have a long tail of big values, so the median describes the typical case better.

SQLite has no MEDIAN function. You can build one from window functions: number the rows in order, count them, and keep the middle one or two.

Result: 5 rows
job_familyoffersmedian_salary
Engineering457750
Data1154500
Product1453500
Design948500
Sales633500
How the middle-row trick works, using whole-number division. With 5 rows: (5+1)/2 = 3 and (5+2)/2 = 3, so just row 3. With 6 rows: (6+1)/2 = 3 and (6+2)/2 = 4, so rows 3 and 4, and AVG takes the halfway point.

Percentiles

A percentile generalises the median. The 90th percentile is the value that 90% of rows are at or below. The median is the 50th percentile. One simple method, called “nearest rank”: take the row at position 0.9 × n, rounded up.

Result: 1 row
offersp90_salary
4474000
(9 * n + 9) / 10 is a whole-number way to round 0.9 × n up. With 44 salaries, 0.9 × 44 = 39.6, so row 40.
Other databases: Snowflake, DuckDB, Oracle and Redshift have MEDIAN(x). Postgres and Snowflake have PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) (it blends the two middle values) and PERCENTILE_DISC (it picks a real value). BigQuery has PERCENTILE_CONT(x, 0.5) OVER () and APPROX_QUANTILES(x, 100)[OFFSET(90)]. Different methods can give slightly different answers on small data.

Common mistakes

  • Reporting an average when the data has a long tail. Show the median, or both.
  • Forgetting to drop NULLs before numbering. They would be counted in n and sorted first.
  • Medians do not add up. The median of two groups is not the average of their medians.

Try it yourself

Exercise 17.1. What is the median salary of all accepted offers?

Hint: Same method, with no PARTITION BY and WHERE status = 'accepted'.

Show the answer
Result: 1 row
median_salary
48500

37 accepted offers have a salary, an odd number, so this is row 19 exactly.

Exercise 17.2. Show the median salary and the average salary per level, side by side.

Hint: Add AVG(base_salary) OVER (PARTITION BY level) as a column in the CTE.

Show the answer
Result: 3 rows
levelmedian_salaryavg_salary
Junior4000040237
Mid5400053786
Senior7400074682

Where the average sits well above the median, a few high salaries are pulling it up.

18 How to structure a long query

A query that someone else can read, check and trust is worth more than a clever one. A good habit list:

Result: 5 rows
job_familyoffersmedian_salary
Data554500
Design568000
Engineering352000
Product266500
Sales334000
Anyone can follow it: the comment says what it answers, each step says what one row means, and the filtering happens once, at the top.

A check that reconciles

The offers column above should add up to the total number of 2024 accepted offers with a salary. Check it with a second, simpler query:

Result: 1 row
sum_of_partstotalcheck_result
1818OK
If a later change adds a join that duplicates rows, this flips to MISMATCH. Teams often keep checks like this next to the main query, or as automated tests.

Try it yourself

Exercise 18.1. Write a check that the number of offers per company, added up, equals the total number of offers in the table.

Hint: A CTE of counts per company, then compare its SUM with COUNT(*) on offers.

Show the answer
Result: 1 row
sum_of_partstotal
4545

Both 45. If they ever differ, something between the steps is losing or adding rows.

19 Ten practice questions

Mixed, interview-style, easiest first. Write your answer, run it, then open the model answer. There is often more than one right answer; if yours gives the same result, it counts.

  1. Easy How many companies are based in Dublin?

    Hint: COUNT(*) with WHERE.

    Show the answer
    Result: 1 row
    dublin_companies
    3

    Filter, then count.

  2. Easy List accepted offers paying more than 70000, highest first, with company names.

    Hint: JOIN, WHERE with two conditions, ORDER BY DESC.

    Show the answer
    Result: 6 rows
    namejob_familylevelbase_salary
    Umberfield SoftwareProductSenior92000
    Copperleaf FoodsDataSenior83000
    Saltmarsh StoresDataSenior75000
    Copperleaf FoodsDataSenior74000
    Umberfield SoftwareDesignSenior74000
    Quillstone MediaProductSenior73500

    A join for the name, a filter for the rest.

  3. Easy What is the average salary per job family, rounded to a whole number, highest first?

    Hint: GROUP BY job_family. Say what happens to offer 7.

    Show the answer
    Result: 5 rows
    job_familyoffers_with_salaryavg_salary
    Engineering457125
    Product1456821
    Data1155727
    Design954389
    Sales635417

    AVG skips the NULL salary; showing COUNT(base_salary) makes that visible.

  4. Medium Which companies have never made an offer?

    Hint: LEFT JOIN and IS NULL, or NOT IN.

    Show the answer
    Result: 1 row
    company_idname
    12Zillmere Robotics

    The anti-join. NOT EXISTS works too.

  5. Medium What share of each company's offers were accepted? Show it as a percentage with one decimal place, lowest first.

    Hint: SUM(CASE ...) over COUNT(*), times 100.0.

    Show the answer
    Result: 11 rows
    nameoffersaccept_pct
    Willowby Insurance450
    Kettlebrook Bank366.7
    Larkspur Freight666.7
    Pixelmoor Games366.7
    Umberfield Software580
    Brightwell Analytics3100
    Copperleaf Foods5100
    Glenvarra Energy2100
    Harbourlight Health5100
    Quillstone Media2100
    Saltmarsh Stores7100

    100.0 avoids whole-number division, which would round most rates to 0.

  6. Medium How many offers were made in each year and quarter?

    Hint: strftime for the year, the (month + 2) / 3 trick for the quarter.

    Show the answer
    Result: 8 rows
    yearquarteroffers
    2023112
    202322
    2023311
    202341
    202415
    202426
    202435
    202443

    Group by both parts so Q1 2023 and Q1 2024 stay apart.

  7. Medium Find rows in offers that may be duplicates.

    Hint: Group on every column except the ID and keep groups with more than one row.

    Show the answer
    Result: 1 row
    company_idjob_familylevelbase_salaryoffered_atstatuscopiesfirst_idlast_id
    2ProductJunior480002023-07-27accepted21819

    Showing the IDs makes it easy to go and check the raw rows.

  8. Hard Find the highest-paid offer in each job family, with the company name. If two tie, show both.

    Hint: RANK (not ROW_NUMBER) in a CTE, then join for the name.

    Show the answer
    Result: 5 rows
    job_familynameoffer_idbase_salary
    DataCopperleaf Foods2683000
    DesignUmberfield Software4374000
    EngineeringUmberfield Software1569000
    ProductUmberfield Software4592000
    SalesSaltmarsh Stores942500

    RANK keeps ties; ROW_NUMBER would quietly drop one.

  9. Hard For each company, show the number of offers, the number of employees and the total offer pay, with no double counting.

    Hint: Aggregate each table to one row per company in its own CTE, then LEFT JOIN to companies.

    Show the answer
    Result: 12 rows
    nameoffersemployeesoffer_pay
    Brightwell Analytics31143000
    Copperleaf Foods53316500
    Glenvarra Energy2398500
    Harbourlight Health52227500
    Kettlebrook Bank32116500
    Larkspur Freight62290500
    Pixelmoor Games32147500
    Quillstone Media23127000
    Saltmarsh Stores75348000
    Umberfield Software52364000
    Willowby Insurance43160000
    Zillmere Robotics020

    Joining both raw tables at once would multiply offers by employees. Pre-aggregating keeps every join one-to-one.

  10. Hard What is the median accepted salary in each industry? Only show industries with at least 3 accepted offers that have a salary.

    Hint: Join for industry, number rows per industry, keep the middle, and filter on n.

    Show the answer
    Result: 5 rows
    industryoffersmedian_salary
    Tech968000
    Logistics357500
    Retail1248000
    Health545000
    Finance440250

    Filtering on n removes industries too small to say much. In Postgres you would use PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY base_salary) with GROUP BY industry.

20 Glossary

Table
A grid of data with named columns, like one sheet of a spreadsheet.
Row
One line across a table. One thing: one offer, one company.
Column
One kind of fact, running down the table.
Database
A set of tables kept together and linked by keys.
SQL
Structured Query Language: the language for asking a database questions.
Query
One question written in SQL. It returns a result table.
Primary key
A column whose value is different on every row, such as offer_id.
Foreign key
A column that points at another table's primary key, such as company_id in offers.
NULL
No value: missing or unknown. Test it with IS NULL.
Alias
A temporary name given with AS, for a column or a table.
Aggregate
A function that turns many rows into one value: COUNT, SUM, AVG, MIN, MAX.
GROUP BY
Splits rows into piles and returns one row per pile.
HAVING
A filter on groups, after GROUP BY.
Join
Puts matching rows from two tables side by side.
INNER JOIN
Keeps only rows that match on both sides.
LEFT JOIN
Keeps every row from the first table, with NULLs where nothing matched.
Grain
What one row of a table or result stands for.
Fan-out
When a join multiplies rows, so totals come out too big.
CTE
A named step written with WITH ... AS ( ... ).
Subquery
A query inside brackets, inside another query.
Window function
A calculation over a group of related rows that keeps every row. Uses OVER.
Partition
The groups a window function works within (PARTITION BY).
Median
The middle value when sorted. Less affected by extreme values than the average.
Percentile
The value a given share of rows are at or below. The median is the 50th.
Dialect
One database's version of SQL. The basics match; functions and dates differ.

Where SQLite differs from other databases

TaskSQLite (this page)PostgresSnowflakeBigQuery
Year of a datestrftime('%Y', d)EXTRACT(YEAR FROM d)YEAR(d)EXTRACT(YEAR FROM d)
Start of quarter(work it out from the month)DATE_TRUNC('quarter', d)DATE_TRUNC('quarter', d)DATE_TRUNC(d, QUARTER)
Days betweenjulianday(b) - julianday(a)b - aDATEDIFF('day', a, b)DATE_DIFF(b, a, DAY)
Medianwindow-function methodPERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x)MEDIAN(x)PERCENTILE_CONT(x, 0.5) OVER ()
Case-insensitive matchLIKEILIKEILIKELOWER(x) LIKE ...
Whole-number division5 / 2 = 25 / 2 = 25 / 2 = 2.55 / 2 = 2.5

See also Data interview questions.