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.
- Tables and SQL
- Practice data
- SELECT, FROM
- WHERE
- NULL
- ORDER BY, LIMIT
- DISTINCT
- COUNT, SUM, AVG
- GROUP BY
- HAVING
- CASE WHEN
- JOINs
- Grain
- Dates
- CTEs (WITH)
- Window functions
- Median, percentiles
- Long queries
- 10 practice questions
- 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.
| offer_id | company_id | job_family | base_salary |
|---|---|---|---|
| 1 | 4 | Sales | 33000 |
| 2 | 11 | Data | 37000 |
| 3 | 10 | Product | 61000 |
- A row is one line across the table. It describes one thing. Here, one row is one job offer.
- A column is one kind of fact, running down the table.
base_salaryis a column: every row has a value for it. - A value (or cell) is where a row and a column meet. Offer 1 has a base salary of 33000.
- A database is a set of tables kept together. The tables are linked by shared columns, usually IDs. Above,
company_id4 points to a row in a separate table of companies.
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.
| name | city |
|---|---|
| Brightwell Analytics | Dublin |
| Copperleaf Foods | Cork |
| Harbourlight Health | Galway |
| Kettlebrook Bank | Dublin |
| Pixelmoor Games | Dublin |
| Quillstone Media | London |
| Glenvarra Energy | Cork |
| Saltmarsh Stores | Limerick |
| Larkspur Freight | NULL |
| Umberfield Software | London |
| Willowby Insurance | Galway |
| Zillmere Robotics | Berlin |
2 The practice data
There are three tables. The database is SQLite, a small free database that runs inside this page.
companies: one row per company
company_id-- a number that identifies the company. No two companies share one. A column like this is called a primary key.name,industry,city-- text.size_band-- Small, Medium or Large.
| company_id | name | industry | city | size_band |
|---|---|---|---|---|
| 1 | Brightwell Analytics | Tech | Dublin | Medium |
| 2 | Copperleaf Foods | Retail | Cork | Large |
| 3 | Harbourlight Health | Health | Galway | Large |
| 4 | Kettlebrook Bank | Finance | Dublin | Large |
| 5 | Pixelmoor Games | Tech | Dublin | Small |
| 6 | Quillstone Media | Media | London | Small |
| 7 | Glenvarra Energy | Energy | Cork | Medium |
| 8 | Saltmarsh Stores | Retail | Limerick | Medium |
| 9 | Larkspur Freight | Logistics | NULL | Medium |
| 10 | Umberfield Software | Tech | London | Large |
| 11 | Willowby Insurance | Finance | Galway | Small |
| 12 | Zillmere Robotics | Tech | Berlin | Small |
offers: one row per job offer
offer_id-- the primary key of this table.company_id-- which company made the offer. It matchescompany_idin companies. A column that points at another table's key is called a foreign key.job_family-- Data, Engineering, Product, Design or Sales.level-- Junior, Mid or Senior.base_salary-- yearly pay in euro, a whole number.offered_at-- the date the offer was made.accepted_at-- the date it was accepted, empty if it was not.status-- accepted, declined or pending.
| offer_id | company_id | job_family | level | base_salary | offered_at | accepted_at | status |
|---|---|---|---|---|---|---|---|
| 1 | 4 | Sales | Junior | 33000 | 2023-01-05 | 2023-01-13 | accepted |
| 2 | 11 | Data | Junior | 37000 | 2023-01-12 | 2023-01-25 | accepted |
| 3 | 10 | Product | Mid | 61000 | 2023-01-16 | NULL | pending |
| 4 | 6 | Product | Mid | 53500 | 2023-01-31 | 2023-02-13 | accepted |
| 5 | 2 | Data | Senior | 74000 | 2023-02-06 | 2023-02-10 | accepted |
| 6 | 8 | Data | Junior | 41500 | 2023-02-23 | 2023-03-07 | accepted |
| 7 | 9 | Design | Junior | NULL | 2023-03-12 | 2023-03-20 | accepted |
| 8 | 3 | Design | Mid | 48500 | 2023-03-15 | 2023-03-26 | accepted |
| 9 | 8 | Sales | Mid | 42500 | 2023-03-17 | 2023-03-21 | accepted |
| 10 | 6 | Product | Senior | 73500 | 2023-03-18 | 2023-03-28 | accepted |
| 11 | 11 | Product | Junior | 40000 | 2023-03-21 | NULL | declined |
| 12 | 5 | Product | Mid | 53500 | 2023-03-27 | NULL | declined |
| 13 | 11 | Design | Mid | 43500 | 2023-04-17 | 2023-04-26 | accepted |
| 14 | 9 | Product | Mid | 58500 | 2023-05-15 | 2023-05-18 | accepted |
| 15 | 10 | Engineering | Mid | 69000 | 2023-07-21 | 2023-07-28 | accepted |
| 16 | 9 | Design | Mid | 48500 | 2023-07-23 | NULL | declined |
| 17 | 11 | Product | Junior | 39500 | 2023-07-25 | NULL | declined |
| 18 | 2 | Product | Junior | 48000 | 2023-07-27 | 2023-08-09 | accepted |
| 19 | 2 | Product | Junior | 48000 | 2023-07-27 | 2023-08-09 | accepted |
| 20 | 1 | Design | Junior | 38000 | 2023-08-03 | 2023-08-11 | accepted |
| 21 | 9 | Product | Mid | 57500 | 2023-09-05 | 2023-09-16 | accepted |
| 22 | 8 | Data | Junior | 38500 | 2023-09-13 | 2023-09-16 | accepted |
| 23 | 9 | Product | Senior | 85000 | 2023-09-13 | NULL | declined |
| 24 | 8 | Product | Junior | 44500 | 2023-09-21 | 2023-10-01 | accepted |
| 25 | 5 | Data | Senior | 64500 | 2023-09-22 | 2023-10-02 | accepted |
| 26 | 2 | Data | Senior | 83000 | 2023-12-05 | 2023-12-17 | accepted |
| 27 | 4 | Sales | Junior | 31500 | 2024-01-02 | NULL | declined |
| 28 | 7 | Data | Mid | 54500 | 2024-01-31 | 2024-02-01 | accepted |
| 29 | 8 | Design | Senior | 64000 | 2024-01-31 | 2024-02-03 | accepted |
| 30 | 2 | Engineering | Mid | 63500 | 2024-02-09 | 2024-02-13 | accepted |
| 31 | 3 | Sales | Junior | 34000 | 2024-03-27 | 2024-03-31 | accepted |
| 32 | 1 | Design | Junior | 36500 | 2024-04-03 | 2024-04-15 | accepted |
| 33 | 9 | Product | Junior | 41000 | 2024-04-08 | 2024-04-20 | accepted |
| 34 | 5 | Sales | Junior | 29500 | 2024-05-07 | 2024-05-19 | accepted |
| 35 | 3 | Data | Junior | 43000 | 2024-05-08 | 2024-05-13 | accepted |
| 36 | 3 | Data | Mid | 57000 | 2024-05-12 | 2024-05-13 | accepted |
| 37 | 10 | Design | Senior | 68000 | 2024-05-26 | 2024-06-05 | accepted |
| 38 | 8 | Sales | Mid | 42000 | 2024-07-08 | 2024-07-21 | accepted |
| 39 | 3 | Data | Junior | 45000 | 2024-08-29 | 2024-08-30 | accepted |
| 40 | 4 | Engineering | Junior | 52000 | 2024-09-08 | 2024-09-10 | accepted |
| 41 | 1 | Design | Senior | 68500 | 2024-09-22 | 2024-10-02 | accepted |
| 42 | 7 | Engineering | Junior | 44000 | 2024-09-29 | 2024-10-09 | accepted |
| 43 | 10 | Design | Senior | 74000 | 2024-12-08 | 2024-12-11 | accepted |
| 44 | 8 | Data | Senior | 75000 | 2024-12-21 | 2024-12-27 | accepted |
| 45 | 10 | Product | Senior | 92000 | 2024-12-29 | 2025-01-03 | accepted |
employees: one row per person who works at a company
employee_id,company_id,job_family,level,start_date.
| employee_id | company_id | job_family | level | start_date |
|---|---|---|---|---|
| 1 | 1 | Data | Junior | 2019-06-19 |
| 2 | 2 | Product | Mid | 2022-06-19 |
| 3 | 2 | Sales | Junior | 2020-07-10 |
| 4 | 2 | Design | Mid | 2019-04-12 |
| 5 | 3 | Product | Junior | 2020-07-31 |
| 6 | 3 | Data | Senior | 2020-04-17 |
| 7 | 4 | Design | Junior | 2023-02-19 |
| 8 | 4 | Data | Mid | 2021-03-27 |
| 9 | 5 | Design | Junior | 2019-02-14 |
| 10 | 5 | Design | Mid | 2019-05-29 |
| 11 | 6 | Engineering | Junior | 2022-11-17 |
| 12 | 6 | Sales | Mid | 2024-11-01 |
| 13 | 6 | Sales | Mid | 2020-10-14 |
| 14 | 7 | Design | Senior | 2021-07-06 |
| 15 | 7 | Data | Mid | 2023-05-09 |
| 16 | 7 | Engineering | Mid | 2021-03-17 |
| 17 | 8 | Data | Mid | 2024-08-20 |
| 18 | 8 | Product | Mid | 2021-04-19 |
| 19 | 8 | Data | Mid | 2020-05-20 |
| 20 | 8 | Engineering | Junior | 2023-05-18 |
| 21 | 8 | Data | Senior | 2022-08-05 |
| 22 | 9 | Product | Senior | 2019-03-06 |
| 23 | 9 | Product | Mid | 2019-06-02 |
| 24 | 10 | Design | Mid | 2023-09-23 |
| 25 | 10 | Product | Mid | 2019-04-27 |
| 26 | 11 | Engineering | Senior | 2019-09-20 |
| 27 | 11 | Design | Senior | 2020-12-09 |
| 28 | 11 | Sales | Mid | 2020-07-29 |
| 29 | 12 | Design | Junior | 2024-10-16 |
| 30 | 12 | Sales | Senior | 2023-12-08 |
Traps hidden on purpose
Real data is messy, so this data is too. These come up again later:
- Larkspur Freight (company 9) has no city. The cell is empty, which SQL calls
NULL. - Offer 7 was accepted but has no salary recorded.
- Offers 18 and 19 are identical apart from their ID. Two real hires, or one offer typed in twice? The data alone cannot say.
- Zillmere Robotics (company 12) has employees but has made no offers.
- Offer 45 was made in 2024 but accepted in 2025.
Sandbox
A free editor. Try anything here, now or later.
| employee_id | company_id | job_family | level | start_date |
|---|---|---|---|---|
| 17 | 8 | Data | Mid | 2024-08-20 |
| 18 | 8 | Product | Mid | 2021-04-19 |
| 19 | 8 | Data | Mid | 2020-05-20 |
| 20 | 8 | Engineering | Junior | 2023-05-18 |
| 21 | 8 | Data | Senior | 2022-08-05 |
3 SELECT and FROM
Every query you write starts from two words:
SELECT-- which columns you want to see.FROM-- which table they live in.
A few rules that apply to everything on this page:
- Words like
SELECTandFROMare keywords. Writing them in capitals is a habit that makes queries easier to read.selectworks just as well. - Spaces and new lines do not matter. Put each part on its own line so it is easy to read.
- A semicolon
;marks the end of a query. One query on its own runs fine without it. - Text values go in single quotes:
'Dublin'. Numbers do not:50000. - Two dashes
--start a comment. The database ignores everything after them on that line. Comments are notes for people.
Pick columns, or take them all
| name | industry |
|---|---|
| Brightwell Analytics | Tech |
| Copperleaf Foods | Retail |
| Harbourlight Health | Health |
| Kettlebrook Bank | Finance |
| Pixelmoor Games | Tech |
| Quillstone Media | Media |
| Glenvarra Energy | Energy |
| Saltmarsh Stores | Retail |
| Larkspur Freight | Logistics |
| Umberfield Software | Tech |
| Willowby Insurance | Finance |
| Zillmere Robotics | Tech |
| company_id | name | industry | city | size_band |
|---|---|---|---|---|
| 1 | Brightwell Analytics | Tech | Dublin | Medium |
| 2 | Copperleaf Foods | Retail | Cork | Large |
| 3 | Harbourlight Health | Health | Galway | Large |
| 4 | Kettlebrook Bank | Finance | Dublin | Large |
| 5 | Pixelmoor Games | Tech | Dublin | Small |
| 6 | Quillstone Media | Media | London | Small |
| 7 | Glenvarra Energy | Energy | Cork | Medium |
| 8 | Saltmarsh Stores | Retail | Limerick | Medium |
| 9 | Larkspur Freight | Logistics | NULL | Medium |
| 10 | Umberfield Software | Tech | London | Large |
| 11 | Willowby Insurance | Finance | Galway | Small |
| 12 | Zillmere Robotics | Tech | Berlin | Small |
* 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.
| offer_id | base_salary | monthly | monthly_exact | monthly_rounded |
|---|---|---|---|---|
| 1 | 33000 | 2750 | 2750 | 2750 |
| 2 | 37000 | 3083 | 3083.3333333333335 | 3083.33 |
| 3 | 61000 | 5083 | 5083.333333333333 | 5083.33 |
| 4 | 53500 | 4458 | 4458.333333333333 | 4458.33 |
| 5 | 74000 | 6166 | 6166.666666666667 | 6166.67 |
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.
| company | home city |
|---|---|
| Brightwell Analytics | Dublin |
| Copperleaf Foods | Cork |
| Harbourlight Health | Galway |
| Kettlebrook Bank | Dublin |
| Pixelmoor Games | Dublin |
| Quillstone Media | London |
| Glenvarra Energy | Cork |
| Saltmarsh Stores | Limerick |
| Larkspur Freight | NULL |
| Umberfield Software | London |
| Willowby Insurance | Galway |
| Zillmere Robotics | Berlin |
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 industrydoes not fail. It quietly showsnameunder the headingindustry, because SQL reads it as an alias. - A comma after the last column:
SELECT name, city, FROM companiesis 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 / 2is 2. Use5 / 2.0or5 * 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
| name | size_band |
|---|---|
| Brightwell Analytics | Medium |
| Copperleaf Foods | Large |
| Harbourlight Health | Large |
| Kettlebrook Bank | Large |
| Pixelmoor Games | Small |
| Quillstone Media | Small |
| Glenvarra Energy | Medium |
| Saltmarsh Stores | Medium |
| Larkspur Freight | Medium |
| Umberfield Software | Large |
| Willowby Insurance | Small |
| Zillmere Robotics | Small |
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
| offer_id | job_family | base_salary | weekly_pay |
|---|---|---|---|
| 1 | Sales | 33000 | 634.62 |
| 2 | Data | 37000 | 711.54 |
| 3 | Product | 61000 | 1173.08 |
| 4 | Product | 53500 | 1028.85 |
| 5 | Data | 74000 | 1423.08 |
| 6 | Data | 41500 | 798.08 |
| 7 | Design | NULL | NULL |
| 8 | Design | 48500 | 932.69 |
| 9 | Sales | 42500 | 817.31 |
| 10 | Product | 73500 | 1413.46 |
| 11 | Product | 40000 | 769.23 |
| 12 | Product | 53500 | 1028.85 |
| 13 | Design | 43500 | 836.54 |
| 14 | Product | 58500 | 1125 |
| 15 | Engineering | 69000 | 1326.92 |
| 16 | Design | 48500 | 932.69 |
| 17 | Product | 39500 | 759.62 |
| 18 | Product | 48000 | 923.08 |
| 19 | Product | 48000 | 923.08 |
| 20 | Design | 38000 | 730.77 |
| 21 | Product | 57500 | 1105.77 |
| 22 | Data | 38500 | 740.38 |
| 23 | Product | 85000 | 1634.62 |
| 24 | Product | 44500 | 855.77 |
| 25 | Data | 64500 | 1240.38 |
| 26 | Data | 83000 | 1596.15 |
| 27 | Sales | 31500 | 605.77 |
| 28 | Data | 54500 | 1048.08 |
| 29 | Design | 64000 | 1230.77 |
| 30 | Engineering | 63500 | 1221.15 |
| 31 | Sales | 34000 | 653.85 |
| 32 | Design | 36500 | 701.92 |
| 33 | Product | 41000 | 788.46 |
| 34 | Sales | 29500 | 567.31 |
| 35 | Data | 43000 | 826.92 |
| 36 | Data | 57000 | 1096.15 |
| 37 | Design | 68000 | 1307.69 |
| 38 | Sales | 42000 | 807.69 |
| 39 | Data | 45000 | 865.38 |
| 40 | Engineering | 52000 | 1000 |
| 41 | Design | 68500 | 1317.31 |
| 42 | Engineering | 44000 | 846.15 |
| 43 | Design | 74000 | 1423.08 |
| 44 | Data | 75000 | 1442.31 |
| 45 | Product | 92000 | 1769.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
| company | sector |
|---|---|
| Brightwell Analytics | Tech |
| Copperleaf Foods | Retail |
| Harbourlight Health | Health |
| Kettlebrook Bank | Finance |
| Pixelmoor Games | Tech |
| Quillstone Media | Media |
| Glenvarra Energy | Energy |
| Saltmarsh Stores | Retail |
| Larkspur Freight | Logistics |
| Umberfield Software | Tech |
| Willowby Insurance | Finance |
| Zillmere Robotics | Tech |
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.
| name | city |
|---|---|
| Brightwell Analytics | Dublin |
| Kettlebrook Bank | Dublin |
| Pixelmoor Games | Dublin |
= are exact: 'dublin' in lower case finds nothing.The comparison signs
=equal,<>not equal (!=also works)>greater than,<less than,>=at least,<=at mostBETWEEN 40000 AND 50000-- from 40000 to 50000, including both endsIN ('Data', 'Product')-- matches any value in the listLIKE 'S%'-- a text pattern.%means “any number of characters”,_means “exactly one character”.
| offer_id | job_family | base_salary |
|---|---|---|
| 6 | Data | 41500 |
| 9 | Sales | 42500 |
| 11 | Product | 40000 |
| 13 | Design | 43500 |
| 24 | Product | 44500 |
| 33 | Product | 41000 |
| 35 | Data | 43000 |
| 38 | Sales | 42000 |
| 39 | Data | 45000 |
| 42 | Engineering | 44000 |
| offer_id | job_family | status |
|---|---|---|
| 27 | Sales | declined |
IN is a short way of writing job_family = 'Engineering' OR job_family = 'Sales'.| name |
|---|
| Brightwell Analytics |
| Copperleaf Foods |
| Pixelmoor Games |
| Quillstone Media |
| Saltmarsh Stores |
| Larkspur Freight |
| Umberfield Software |
| Willowby Insurance |
| Zillmere Robotics |
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.
| offer_id | job_family | base_salary |
|---|---|---|
| 2 | Data | 37000 |
| 3 | Product | 61000 |
| 5 | Data | 74000 |
| 6 | Data | 41500 |
| 10 | Product | 73500 |
| 22 | Data | 38500 |
| 23 | Product | 85000 |
| 25 | Data | 64500 |
| 26 | Data | 83000 |
| 28 | Data | 54500 |
| 35 | Data | 43000 |
| 36 | Data | 57000 |
| 39 | Data | 45000 |
| 44 | Data | 75000 |
| 45 | Product | 92000 |
| offer_id | job_family | base_salary |
|---|---|---|
| 3 | Product | 61000 |
| 5 | Data | 74000 |
| 10 | Product | 73500 |
| 23 | Product | 85000 |
| 25 | Data | 64500 |
| 26 | Data | 83000 |
| 44 | Data | 75000 |
| 45 | Product | 92000 |
Common mistakes
- Forgetting quotes around text:
WHERE city = Dublinmakes SQL look for a column called Dublin. - Mixing AND and OR without brackets.
- Forgetting the
%:LIKE 'Bank'only matches the exact word Bank. - Expecting
BETWEENto 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
| 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
| offer_id | job_family | base_salary |
|---|---|---|
| 5 | Data | 74000 |
| 10 | Product | 73500 |
| 26 | Data | 83000 |
| 43 | Design | 74000 |
| 44 | Data | 75000 |
| 45 | Product | 92000 |
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
| name | city |
|---|---|
| Copperleaf Foods | Cork |
| Harbourlight Health | Galway |
| Kettlebrook Bank | Dublin |
| Glenvarra Energy | Cork |
| Willowby Insurance | Galway |
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.
| name | city |
|---|
| name | city |
|---|---|
| Larkspur Freight | NULL |
IS NULL and IS NOT NULL. They are the only tests that give a clear yes or no for missing values.| name | city |
|---|---|
| Copperleaf Foods | Cork |
| Harbourlight Health | Galway |
| Quillstone Media | London |
| Glenvarra Energy | Cork |
| Saltmarsh Stores | Limerick |
| Umberfield Software | London |
| Willowby Insurance | Galway |
| Zillmere Robotics | Berlin |
OR city IS NULL.Replacing NULL with something readable
| name | city |
|---|---|
| Brightwell Analytics | Dublin |
| Copperleaf Foods | Cork |
| Harbourlight Health | Galway |
| Kettlebrook Bank | Dublin |
| Pixelmoor Games | Dublin |
| Quillstone Media | London |
| Glenvarra Energy | Cork |
| Saltmarsh Stores | Limerick |
| Larkspur Freight | Not recorded |
| Umberfield Software | London |
| Willowby Insurance | Galway |
| Zillmere Robotics | Berlin |
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
= NULLor<> NULL. AlwaysIS 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
| offer_id | status | accepted_at |
|---|---|---|
| 3 | pending | NULL |
| 11 | declined | NULL |
| 12 | declined | NULL |
| 16 | declined | NULL |
| 17 | declined | NULL |
| 23 | declined | NULL |
| 27 | declined | NULL |
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
| offer_id | company_id | job_family | level | base_salary | offered_at | accepted_at | status |
|---|---|---|---|---|---|---|---|
| 7 | 9 | Design | Junior | NULL | 2023-03-12 | 2023-03-20 | accepted |
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
| name | city |
|---|---|
| Copperleaf Foods | Cork |
| Harbourlight Health | Galway |
| Quillstone Media | London |
| Glenvarra Energy | Cork |
| Saltmarsh Stores | Limerick |
| Larkspur Freight | NULL |
| Umberfield Software | London |
| Willowby Insurance | Galway |
| Zillmere Robotics | Berlin |
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.
ORDER BY base_salary-- smallest first. This is called ascending (ASC) and it is the default.ORDER BY base_salary DESC-- biggest first (descending).ORDER BY job_family, base_salary DESC-- sort by family; inside each family, biggest salary first.
| offer_id | job_family | base_salary |
|---|---|---|
| 45 | Product | 92000 |
| 23 | Product | 85000 |
| 26 | Data | 83000 |
| 44 | Data | 75000 |
| 5 | Data | 74000 |
| offer_id | job_family | level | base_salary |
|---|---|---|---|
| 15 | Engineering | Mid | 69000 |
| 30 | Engineering | Mid | 63500 |
| 40 | Engineering | Junior | 52000 |
| 42 | Engineering | Junior | 44000 |
| 9 | Sales | Mid | 42500 |
| 38 | Sales | Mid | 42000 |
| 31 | Sales | Junior | 34000 |
| 1 | Sales | Junior | 33000 |
| 27 | Sales | Junior | 31500 |
| 34 | Sales | Junior | 29500 |
SELECT → FROM → WHERE → ORDER BY → LIMIT. Putting them in the wrong order is an error.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 5cuts 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
| offer_id | job_family | base_salary |
|---|---|---|
| 34 | Sales | 29500 |
| 1 | Sales | 33000 |
| 31 | Sales | 34000 |
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
| city | name |
|---|---|
| NULL | Larkspur Freight |
| Berlin | Zillmere Robotics |
| Cork | Copperleaf Foods |
| Cork | Glenvarra Energy |
| Dublin | Brightwell Analytics |
| Dublin | Kettlebrook Bank |
| Dublin | Pixelmoor Games |
| Galway | Harbourlight Health |
| Galway | Willowby Insurance |
| Limerick | Saltmarsh Stores |
| London | Quillstone Media |
| London | Umberfield 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
| offer_id | offered_at | status |
|---|---|---|
| 45 | 2024-12-29 | accepted |
| 44 | 2024-12-21 | accepted |
| 43 | 2024-12-08 | accepted |
| 42 | 2024-09-29 | accepted |
| 41 | 2024-09-22 | accepted |
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?”.
| industry |
|---|
| Energy |
| Finance |
| Health |
| Logistics |
| Media |
| Retail |
| Tech |
| industry | size_band |
|---|---|
| Energy | Medium |
| Finance | Large |
| Finance | Small |
| Health | Large |
| Logistics | Medium |
| Media | Small |
| Retail | Large |
| Retail | Medium |
| Tech | Large |
| Tech | Medium |
| Tech | Small |
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
| 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
| 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.
COUNT(*)-- how many rows.COUNT(column)-- how many rows where that column is not NULL.COUNT(DISTINCT column)-- how many different values.SUM(column)-- the total.AVG(column)-- the average (the mean).MIN(column)andMAX(column)-- the smallest and largest. These work on text and dates too.
| all_offers | with_salary | companies | lowest | highest | average |
|---|---|---|---|---|---|
| 45 | 44 | 11 | 29500 | 92000 | 53159 |
| accepted | total_pay |
|---|---|
| 38 | 1980000 |
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
| 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
| lowest | highest |
|---|---|
| 37000 | 83000 |
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
| 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
| offer_id | job_family | base_salary |
|---|---|---|
| 6 | Data | 41500 |
| 22 | Data | 38500 |
| 44 | Data | 75000 |
| 29 | Design | 64000 |
| 24 | Product | 44500 |
| 9 | Sales | 42500 |
| 38 | Sales | 42000 |
After GROUP BY job_family: 4 rows
| job_family | offers | total |
|---|---|---|
| Data | 3 | 155000 |
| Design | 1 | 64000 |
| Product | 1 | 44500 |
| Sales | 2 | 84500 |
- The database sorts the rows into piles, one pile per job family: 3 Data rows, 1 Design, 1 Product, 2 Sales.
- Each pile becomes one row in the result.
- Aggregates such as
COUNT(*)andSUMare 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...).
| job_family | offers |
|---|---|
| Product | 14 |
| Data | 11 |
| Design | 10 |
| Sales | 6 |
| Engineering | 4 |
ORDER BY offers can use the alias from the SELECT line.| job_family | level | offers | avg_salary |
|---|---|---|---|
| Data | Junior | 5 | 41000 |
| Data | Mid | 2 | 55750 |
| Data | Senior | 4 | 74125 |
| Design | Junior | 3 | 37250 |
| Design | Mid | 3 | 46833 |
| Design | Senior | 4 | 68625 |
| Engineering | Junior | 2 | 48000 |
| Engineering | Mid | 2 | 66250 |
| Product | Junior | 6 | 43500 |
| Product | Mid | 5 | 56800 |
| Product | Senior | 3 | 83500 |
| Sales | Junior | 4 | 32000 |
| Sales | Mid | 2 | 42250 |
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
| status | offers |
|---|---|
| accepted | 38 |
| declined | 6 |
| pending | 1 |
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
| industry | companies |
|---|---|
| Tech | 4 |
| Finance | 2 |
| Retail | 2 |
| Energy | 1 |
| Health | 1 |
| Logistics | 1 |
| Media | 1 |
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
| level | avg_salary |
|---|---|
| Senior | 73650 |
| Mid | 53636 |
| Junior | 40844 |
WHERE filters rows before they go into the piles.
10 HAVING vs WHERE
Both are filters. The difference is when they run.
WHEREfilters rows, before they are grouped.HAVINGfilters groups, after they are made. It is the only place you can filter on an aggregate likeCOUNT(*).
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).
| job_family | offers |
|---|---|
| Data | 11 |
| Design | 10 |
| Product | 14 |
| Sales | 6 |
| job_family | accepted | avg_salary |
|---|---|---|
| Data | 11 | 55727 |
| Design | 9 | 55125 |
| Engineering | 4 | 57125 |
| Product | 9 | 57389 |
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
| company_id | offers |
|---|---|
| 8 | 7 |
| 9 | 6 |
| 10 | 5 |
| 3 | 5 |
| 2 | 5 |
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
| level | avg_salary |
|---|---|
| Mid | 53636 |
| Senior | 73650 |
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:
| offer_id | base_salary | pay_band |
|---|---|---|
| 45 | 92000 | High |
| 23 | 85000 | High |
| 26 | 83000 | High |
| 44 | 75000 | High |
| 5 | 74000 | High |
| 43 | 74000 | High |
| 10 | 73500 | High |
| 15 | 69000 | Middle |
| 41 | 68500 | Middle |
| 37 | 68000 | Middle |
| 25 | 64500 | Middle |
| 29 | 64000 | Middle |
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.
| job_family | offers | accepted | accept_pct |
|---|---|---|---|
| Engineering | 4 | 4 | 100 |
| Data | 11 | 11 | 100 |
| Design | 10 | 9 | 90 |
| Sales | 6 | 5 | 83.3 |
| Product | 14 | 9 | 64.3 |
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 > 5orWHEN x <= 5. AddWHEN x IS NULLfirst 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
| name | city | location |
|---|---|---|
| Brightwell Analytics | Dublin | Ireland |
| Copperleaf Foods | Cork | Ireland |
| Harbourlight Health | Galway | Ireland |
| Kettlebrook Bank | Dublin | Ireland |
| Pixelmoor Games | Dublin | Ireland |
| Quillstone Media | London | Abroad |
| Glenvarra Energy | Cork | Ireland |
| Saltmarsh Stores | Limerick | Ireland |
| Larkspur Freight | NULL | Unknown |
| Umberfield Software | London | Abroad |
| Willowby Insurance | Galway | Ireland |
| Zillmere Robotics | Berlin | Abroad |
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
| job_family | accepted | declined |
|---|---|---|
| Data | 11 | 0 |
| Design | 9 | 1 |
| Engineering | 4 | 0 |
| Product | 9 | 4 |
| Sales | 5 | 1 |
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.
INNER JOIN: only rows that match
| company_id | name | offer_id | job_family |
|---|---|---|---|
| 5 | Pixelmoor Games | 12 | Product |
| 5 | Pixelmoor Games | 25 | Data |
| 5 | Pixelmoor Games | 34 | Sales |
| 6 | Quillstone Media | 4 | Product |
| 6 | Quillstone Media | 10 | Product |
JOIN means the same as INNER JOIN.LEFT JOIN: keep everything on the left
| company_id | name | offer_id | job_family |
|---|---|---|---|
| 5 | Pixelmoor Games | 12 | Product |
| 5 | Pixelmoor Games | 25 | Data |
| 5 | Pixelmoor Games | 34 | Sales |
| 6 | Quillstone Media | 4 | Product |
| 6 | Quillstone Media | 10 | Product |
| 12 | Zillmere Robotics | NULL | NULL |
That NULL is useful. To find rows with no match, LEFT JOIN and keep the rows where the right side is NULL:
| name |
|---|
| Zillmere Robotics |
A trap: filtering the right-hand table
| name | offer_id |
|---|---|
| Quillstone Media | 4 |
| Quillstone Media | 10 |
| Pixelmoor Games | 25 |
| Pixelmoor Games | 34 |
NULL = 'accepted' is not true, so WHERE threw it out. The LEFT JOIN has quietly become an INNER JOIN.| name | offer_id |
|---|---|
| Pixelmoor Games | 25 |
| Pixelmoor Games | 34 |
| Quillstone Media | 4 |
| Quillstone Media | 10 |
| Zillmere Robotics | NULL |
ON. Now only accepted offers are matched, and every company is kept.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. UseCOUNT(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
| offer_id | name | city | job_family | base_salary |
|---|---|---|---|---|
| 1 | Kettlebrook Bank | Dublin | Sales | 33000 |
| 2 | Willowby Insurance | Galway | Data | 37000 |
| 4 | Quillstone Media | London | Product | 53500 |
| 5 | Copperleaf Foods | Cork | Data | 74000 |
| 6 | Saltmarsh Stores | Limerick | Data | 41500 |
| 7 | Larkspur Freight | NULL | Design | NULL |
| 8 | Harbourlight Health | Galway | Design | 48500 |
| 9 | Saltmarsh Stores | Limerick | Sales | 42500 |
| 10 | Quillstone Media | London | Product | 73500 |
| 13 | Willowby Insurance | Galway | Design | 43500 |
| 14 | Larkspur Freight | NULL | Product | 58500 |
| 15 | Umberfield Software | London | Engineering | 69000 |
| 18 | Copperleaf Foods | Cork | Product | 48000 |
| 19 | Copperleaf Foods | Cork | Product | 48000 |
| 20 | Brightwell Analytics | Dublin | Design | 38000 |
| 21 | Larkspur Freight | NULL | Product | 57500 |
| 22 | Saltmarsh Stores | Limerick | Data | 38500 |
| 24 | Saltmarsh Stores | Limerick | Product | 44500 |
| 25 | Pixelmoor Games | Dublin | Data | 64500 |
| 26 | Copperleaf Foods | Cork | Data | 83000 |
| 28 | Glenvarra Energy | Cork | Data | 54500 |
| 29 | Saltmarsh Stores | Limerick | Design | 64000 |
| 30 | Copperleaf Foods | Cork | Engineering | 63500 |
| 31 | Harbourlight Health | Galway | Sales | 34000 |
| 32 | Brightwell Analytics | Dublin | Design | 36500 |
| 33 | Larkspur Freight | NULL | Product | 41000 |
| 34 | Pixelmoor Games | Dublin | Sales | 29500 |
| 35 | Harbourlight Health | Galway | Data | 43000 |
| 36 | Harbourlight Health | Galway | Data | 57000 |
| 37 | Umberfield Software | London | Design | 68000 |
| 38 | Saltmarsh Stores | Limerick | Sales | 42000 |
| 39 | Harbourlight Health | Galway | Data | 45000 |
| 40 | Kettlebrook Bank | Dublin | Engineering | 52000 |
| 41 | Brightwell Analytics | Dublin | Design | 68500 |
| 42 | Glenvarra Energy | Cork | Engineering | 44000 |
| 43 | Umberfield Software | London | Design | 74000 |
| 44 | Saltmarsh Stores | Limerick | Data | 75000 |
| 45 | Umberfield Software | London | Product | 92000 |
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
| industry | offers |
|---|---|
| Retail | 12 |
| Tech | 11 |
| Finance | 7 |
| Logistics | 6 |
| Health | 5 |
| Media | 2 |
| Energy | 2 |
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
| name | offers |
|---|---|
| Saltmarsh Stores | 7 |
| Larkspur Freight | 6 |
| Copperleaf Foods | 5 |
| Harbourlight Health | 5 |
| Umberfield Software | 5 |
| Willowby Insurance | 4 |
| Brightwell Analytics | 3 |
| Kettlebrook Bank | 3 |
| Pixelmoor Games | 3 |
| Glenvarra Energy | 2 |
| Quillstone Media | 2 |
| Zillmere Robotics | 0 |
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.
- companies: one row per company.
- offers: one row per offer.
- employees: one row per employee.
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.
| name | offers | employees | total_offer_pay |
|---|---|---|---|
| Saltmarsh Stores | 35 | 35 | 1740000 |
| name | offers | employees |
|---|---|---|
| Saltmarsh Stores | 7 | 5 |
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:
| row_count | distinct_ids |
|---|---|
| 45 | 45 |
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
| company_id | job_family | level | base_salary | offered_at | accepted_at | status | copies |
|---|---|---|---|---|---|---|---|
| 2 | Product | Junior | 48000 | 2023-07-27 | 2023-08-09 | accepted | 2 |
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
| row_count | distinct_ids |
|---|---|
| 30 | 30 |
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.
| offer_id | accepted_at | year | month | quarter |
|---|---|---|---|---|
| 1 | 2023-01-13 | 2023 | 2023-01 | 1 |
| 2 | 2023-01-25 | 2023 | 2023-01 | 1 |
| 4 | 2023-02-13 | 2023 | 2023-02 | 1 |
| 5 | 2023-02-10 | 2023 | 2023-02 | 1 |
| 6 | 2023-03-07 | 2023 | 2023-03 | 1 |
| 7 | 2023-03-20 | 2023 | 2023-03 | 1 |
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.| year | quarter | accepted_offers |
|---|---|---|
| 2023 | 1 | 9 |
| 2023 | 2 | 2 |
| 2023 | 3 | 6 |
| 2023 | 4 | 3 |
| 2024 | 1 | 4 |
| 2024 | 2 | 6 |
| 2024 | 3 | 3 |
| 2024 | 4 | 4 |
| 2025 | 1 | 1 |
Days between two dates
| offer_id | offered_at | accepted_at | days_to_accept |
|---|---|---|---|
| 2 | 2023-01-12 | 2023-01-25 | 13 |
| 4 | 2023-01-31 | 2023-02-13 | 13 |
| 18 | 2023-07-27 | 2023-08-09 | 13 |
| 19 | 2023-07-27 | 2023-08-09 | 13 |
| 38 | 2024-07-08 | 2024-07-21 | 13 |
julianday turns a date into a day number, so subtracting two gives the days between them.Filtering a date range
| offers_made_in_2024 |
|---|
| 19 |
| rows_found |
|---|
| 0 |
strftime returns the text '2024', and SQLite says text is never equal to the number 2024. Write = '2024' with quotes.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
| 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
| month | accepted |
|---|---|
| 2024-02 | 3 |
| 2024-03 | 1 |
| 2024-04 | 2 |
| 2024-05 | 3 |
| 2024-06 | 1 |
| 2024-07 | 1 |
| 2024-08 | 1 |
| 2024-09 | 1 |
| 2024-10 | 2 |
| 2024-12 | 2 |
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
| offer_id | days_to_accept |
|---|---|
| 28 | 1 |
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:
| company_id | accepted_offers | avg_salary |
|---|---|---|
| 10 | 4 | 75750 |
| 6 | 2 | 63500 |
| 2 | 5 | 63300 |
| 9 | 4 | 52333 |
| 8 | 7 | 49714 |
| 7 | 2 | 49250 |
| 1 | 3 | 47667 |
| 5 | 2 | 47000 |
| 3 | 5 | 45500 |
| 4 | 2 | 42500 |
| 11 | 2 | 40250 |
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.
| name | offers | employees | total_offer_pay |
|---|---|---|---|
| Brightwell Analytics | 3 | 1 | 143000 |
| Copperleaf Foods | 5 | 3 | 316500 |
| Harbourlight Health | 5 | 2 | 227500 |
| Kettlebrook Bank | 3 | 2 | 116500 |
| Pixelmoor Games | 3 | 2 | 147500 |
| Quillstone Media | 2 | 3 | 127000 |
| Glenvarra Energy | 2 | 3 | 98500 |
| Saltmarsh Stores | 7 | 5 | 348000 |
| Larkspur Freight | 6 | 2 | 290500 |
| Umberfield Software | 5 | 2 | 364000 |
| Willowby Insurance | 4 | 3 | 160000 |
| Zillmere Robotics | 0 | 2 | NULL |
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
| offer_id | job_family | base_salary | overall_avg |
|---|---|---|---|
| 45 | Product | 92000 | 53514 |
| 26 | Data | 83000 | 53514 |
| 44 | Data | 75000 | 53514 |
| 5 | Data | 74000 | 53514 |
| 43 | Design | 74000 | 53514 |
| 10 | Product | 73500 | 53514 |
| 15 | Engineering | 69000 | 53514 |
| 41 | Design | 68500 | 53514 |
| 37 | Design | 68000 | 53514 |
| 25 | Data | 64500 | 53514 |
| 29 | Design | 64000 | 53514 |
| 30 | Engineering | 63500 | 53514 |
| 14 | Product | 58500 | 53514 |
| 21 | Product | 57500 | 53514 |
| 36 | Data | 57000 | 53514 |
| 28 | Data | 54500 | 53514 |
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
| offers_made | companies |
|---|---|
| 2 | 2 |
| 3 | 3 |
| 4 | 1 |
| 5 | 3 |
| 6 | 1 |
| 7 | 1 |
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:
PARTITION BY job_family-- make piles by job family, like GROUP BY, but keep every row. Leave it out and the whole table is one pile.ORDER BY ...-- the order of rows inside each pile, for anything that counts positions or looks back.
Step 1: an average next to every row
| offer_id | job_family | base_salary | family_avg |
|---|---|---|---|
| 15 | Engineering | 69000 | 57125 |
| 30 | Engineering | 63500 | 57125 |
| 40 | Engineering | 52000 | 57125 |
| 42 | Engineering | 44000 | 57125 |
| 9 | Sales | 42500 | 35417 |
| 38 | Sales | 42000 | 35417 |
| 31 | Sales | 34000 | 35417 |
| 1 | Sales | 33000 | 35417 |
| 27 | Sales | 31500 | 35417 |
| 34 | Sales | 29500 | 35417 |
Step 2: numbering rows: ROW_NUMBER, RANK, DENSE_RANK
| offer_id | base_salary | row_num | rnk | dense_rnk |
|---|---|---|---|---|
| 45 | 92000 | 1 | 1 | 1 |
| 23 | 85000 | 2 | 2 | 2 |
| 10 | 73500 | 3 | 3 | 3 |
| 3 | 61000 | 4 | 4 | 4 |
| 14 | 58500 | 5 | 5 | 5 |
| 21 | 57500 | 6 | 6 | 6 |
| 4 | 53500 | 7 | 7 | 7 |
| 12 | 53500 | 8 | 7 | 7 |
| 18 | 48000 | 9 | 9 | 8 |
| 19 | 48000 | 10 | 9 | 8 |
| 24 | 44500 | 11 | 11 | 9 |
| 33 | 41000 | 12 | 12 | 10 |
| 11 | 40000 | 13 | 13 | 11 |
| 17 | 39500 | 14 | 14 | 12 |
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:
| job_family | offer_id | base_salary |
|---|---|---|
| Data | 26 | 83000 |
| Design | 43 | 74000 |
| Engineering | 15 | 69000 |
| Product | 45 | 92000 |
| Sales | 9 | 42500 |
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.
| quarter | accepted | previous_quarter | change |
|---|---|---|---|
| 2023-Q1 | 9 | NULL | NULL |
| 2023-Q2 | 2 | 9 | -7 |
| 2023-Q3 | 6 | 2 | 4 |
| 2023-Q4 | 3 | 6 | -3 |
| 2024-Q1 | 4 | 3 | 1 |
| 2024-Q2 | 6 | 4 | 2 |
| 2024-Q3 | 3 | 6 | -3 |
| 2024-Q4 | 4 | 3 | 1 |
| 2025-Q1 | 1 | 4 | -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
| month | accepted | running_total |
|---|---|---|
| 2024-02 | 3 | 3 |
| 2024-03 | 1 | 4 |
| 2024-04 | 2 | 6 |
| 2024-05 | 3 | 9 |
| 2024-06 | 1 | 10 |
| 2024-07 | 1 | 11 |
| 2024-08 | 1 | 12 |
| 2024-09 | 1 | 13 |
| 2024-10 | 2 | 15 |
| 2024-12 | 2 | 17 |
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
| company_id | offer_id | offered_at | nth_offer |
|---|---|---|---|
| 1 | 20 | 2023-08-03 | 1 |
| 1 | 32 | 2024-04-03 | 2 |
| 1 | 41 | 2024-09-22 | 3 |
| 2 | 5 | 2023-02-06 | 1 |
| 2 | 18 | 2023-07-27 | 2 |
| 2 | 19 | 2023-07-27 | 3 |
| 2 | 26 | 2023-12-05 | 4 |
| 2 | 30 | 2024-02-09 | 5 |
| 3 | 8 | 2023-03-15 | 1 |
| 3 | 31 | 2024-03-27 | 2 |
| 3 | 35 | 2024-05-08 | 3 |
| 3 | 36 | 2024-05-12 | 4 |
| 3 | 39 | 2024-08-29 | 5 |
| 4 | 1 | 2023-01-05 | 1 |
| 4 | 27 | 2024-01-02 | 2 |
| 4 | 40 | 2024-09-08 | 3 |
| 5 | 12 | 2023-03-27 | 1 |
| 5 | 25 | 2023-09-22 | 2 |
| 5 | 34 | 2024-05-07 | 3 |
| 6 | 4 | 2023-01-31 | 1 |
| 6 | 10 | 2023-03-18 | 2 |
| 7 | 28 | 2024-01-31 | 1 |
| 7 | 42 | 2024-09-29 | 2 |
| 8 | 6 | 2023-02-23 | 1 |
| 8 | 9 | 2023-03-17 | 2 |
| 8 | 22 | 2023-09-13 | 3 |
| 8 | 24 | 2023-09-21 | 4 |
| 8 | 29 | 2024-01-31 | 5 |
| 8 | 38 | 2024-07-08 | 6 |
| 8 | 44 | 2024-12-21 | 7 |
| 9 | 7 | 2023-03-12 | 1 |
| 9 | 14 | 2023-05-15 | 2 |
| 9 | 16 | 2023-07-23 | 3 |
| 9 | 21 | 2023-09-05 | 4 |
| 9 | 23 | 2023-09-13 | 5 |
| 9 | 33 | 2024-04-08 | 6 |
| 10 | 3 | 2023-01-16 | 1 |
| 10 | 15 | 2023-07-21 | 2 |
| 10 | 37 | 2024-05-26 | 3 |
| 10 | 43 | 2024-12-08 | 4 |
| 10 | 45 | 2024-12-29 | 5 |
| 11 | 2 | 2023-01-12 | 1 |
| 11 | 11 | 2023-03-21 | 2 |
| 11 | 13 | 2023-04-17 | 3 |
| 11 | 17 | 2023-07-25 | 4 |
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
| job_family | offer_id | base_salary |
|---|---|---|
| Data | 44 | 75000 |
| Design | 41 | 68500 |
| Engineering | 30 | 63500 |
| Product | 23 | 85000 |
| Sales | 38 | 42000 |
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
| company_id | offer_id | accepted_at | previous_accept | days_since |
|---|---|---|---|---|
| 1 | 20 | 2023-08-11 | NULL | NULL |
| 1 | 32 | 2024-04-15 | 2023-08-11 | 248 |
| 1 | 41 | 2024-10-02 | 2024-04-15 | 170 |
| 2 | 5 | 2023-02-10 | NULL | NULL |
| 2 | 18 | 2023-08-09 | 2023-02-10 | 180 |
| 2 | 19 | 2023-08-09 | 2023-08-09 | 0 |
| 2 | 26 | 2023-12-17 | 2023-08-09 | 130 |
| 2 | 30 | 2024-02-13 | 2023-12-17 | 58 |
| 3 | 8 | 2023-03-26 | NULL | NULL |
| 3 | 31 | 2024-03-31 | 2023-03-26 | 371 |
| 3 | 35 | 2024-05-13 | 2024-03-31 | 43 |
| 3 | 36 | 2024-05-13 | 2024-05-13 | 0 |
| 3 | 39 | 2024-08-30 | 2024-05-13 | 109 |
| 4 | 1 | 2023-01-13 | NULL | NULL |
| 4 | 40 | 2024-09-10 | 2023-01-13 | 606 |
| 5 | 25 | 2023-10-02 | NULL | NULL |
| 5 | 34 | 2024-05-19 | 2023-10-02 | 230 |
| 6 | 4 | 2023-02-13 | NULL | NULL |
| 6 | 10 | 2023-03-28 | 2023-02-13 | 43 |
| 7 | 28 | 2024-02-01 | NULL | NULL |
| 7 | 42 | 2024-10-09 | 2024-02-01 | 251 |
| 8 | 6 | 2023-03-07 | NULL | NULL |
| 8 | 9 | 2023-03-21 | 2023-03-07 | 14 |
| 8 | 22 | 2023-09-16 | 2023-03-21 | 179 |
| 8 | 24 | 2023-10-01 | 2023-09-16 | 15 |
| 8 | 29 | 2024-02-03 | 2023-10-01 | 125 |
| 8 | 38 | 2024-07-21 | 2024-02-03 | 169 |
| 8 | 44 | 2024-12-27 | 2024-07-21 | 159 |
| 9 | 7 | 2023-03-20 | NULL | NULL |
| 9 | 14 | 2023-05-18 | 2023-03-20 | 59 |
| 9 | 21 | 2023-09-16 | 2023-05-18 | 121 |
| 9 | 33 | 2024-04-20 | 2023-09-16 | 217 |
| 10 | 15 | 2023-07-28 | NULL | NULL |
| 10 | 37 | 2024-06-05 | 2023-07-28 | 313 |
| 10 | 43 | 2024-12-11 | 2024-06-05 | 189 |
| 10 | 45 | 2025-01-03 | 2024-12-11 | 23 |
| 11 | 2 | 2023-01-25 | NULL | NULL |
| 11 | 13 | 2023-04-26 | 2023-01-25 | 91 |
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.
| job_family | offers | median_salary |
|---|---|---|
| Engineering | 4 | 57750 |
| Data | 11 | 54500 |
| Product | 14 | 53500 |
| Design | 9 | 48500 |
| Sales | 6 | 33500 |
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.
| offers | p90_salary |
|---|---|
| 44 | 74000 |
(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.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
| 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
| level | median_salary | avg_salary |
|---|---|---|
| Junior | 40000 | 40237 |
| Mid | 54000 | 53786 |
| Senior | 74000 | 74682 |
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:
- Start with a purpose comment. One line on the question it answers, and one on the grain of the final result.
- One CTE per step, each named for what it holds, each with a grain comment.
- Filter early. Drop rows you don't need in the first step, so later steps are smaller and simpler.
- Join on stated keys, and check that the join cannot multiply rows.
- List columns. No
SELECT *in anything you share. - Add checks that reconcile: the parts should add up to a total you can get another way.
| job_family | offers | median_salary |
|---|---|---|
| Data | 5 | 54500 |
| Design | 5 | 68000 |
| Engineering | 3 | 52000 |
| Product | 2 | 66500 |
| Sales | 3 | 34000 |
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:
| sum_of_parts | total | check_result |
|---|---|---|
| 18 | 18 | OK |
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
| sum_of_parts | total |
|---|---|
| 45 | 45 |
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.
Easy How many companies are based in Dublin?
Hint: COUNT(*) with WHERE.
Show the answer
Result: 1 rowdublin_companies 3 Filter, then count.
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 rowsname job_family level base_salary Umberfield Software Product Senior 92000 Copperleaf Foods Data Senior 83000 Saltmarsh Stores Data Senior 75000 Copperleaf Foods Data Senior 74000 Umberfield Software Design Senior 74000 Quillstone Media Product Senior 73500 A join for the name, a filter for the rest.
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 rowsjob_family offers_with_salary avg_salary Engineering 4 57125 Product 14 56821 Data 11 55727 Design 9 54389 Sales 6 35417 AVG skips the NULL salary; showing COUNT(base_salary) makes that visible.
Medium Which companies have never made an offer?
Hint: LEFT JOIN and IS NULL, or NOT IN.
Show the answer
Result: 1 rowcompany_id name 12 Zillmere Robotics The anti-join.
NOT EXISTSworks too.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 rowsname offers accept_pct Willowby Insurance 4 50 Kettlebrook Bank 3 66.7 Larkspur Freight 6 66.7 Pixelmoor Games 3 66.7 Umberfield Software 5 80 Brightwell Analytics 3 100 Copperleaf Foods 5 100 Glenvarra Energy 2 100 Harbourlight Health 5 100 Quillstone Media 2 100 Saltmarsh Stores 7 100 100.0 avoids whole-number division, which would round most rates to 0.
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 rowsyear quarter offers 2023 1 12 2023 2 2 2023 3 11 2023 4 1 2024 1 5 2024 2 6 2024 3 5 2024 4 3 Group by both parts so Q1 2023 and Q1 2024 stay apart.
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 rowcompany_id job_family level base_salary offered_at status copies first_id last_id 2 Product Junior 48000 2023-07-27 accepted 2 18 19 Showing the IDs makes it easy to go and check the raw rows.
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 rowsjob_family name offer_id base_salary Data Copperleaf Foods 26 83000 Design Umberfield Software 43 74000 Engineering Umberfield Software 15 69000 Product Umberfield Software 45 92000 Sales Saltmarsh Stores 9 42500 RANK keeps ties; ROW_NUMBER would quietly drop one.
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 rowsname offers employees offer_pay Brightwell Analytics 3 1 143000 Copperleaf Foods 5 3 316500 Glenvarra Energy 2 3 98500 Harbourlight Health 5 2 227500 Kettlebrook Bank 3 2 116500 Larkspur Freight 6 2 290500 Pixelmoor Games 3 2 147500 Quillstone Media 2 3 127000 Saltmarsh Stores 7 5 348000 Umberfield Software 5 2 364000 Willowby Insurance 4 3 160000 Zillmere Robotics 0 2 0 Joining both raw tables at once would multiply offers by employees. Pre-aggregating keeps every join one-to-one.
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 rowsindustry offers median_salary Tech 9 68000 Logistics 3 57500 Retail 12 48000 Health 5 45000 Finance 4 40250 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
| Task | SQLite (this page) | Postgres | Snowflake | BigQuery |
|---|---|---|---|---|
| Year of a date | strftime('%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 between | julianday(b) - julianday(a) | b - a | DATEDIFF('day', a, b) | DATE_DIFF(b, a, DAY) |
| Median | window-function method | PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) | MEDIAN(x) | PERCENTILE_CONT(x, 0.5) OVER () |
| Case-insensitive match | LIKE | ILIKE | ILIKE | LOWER(x) LIKE ... |
| Whole-number division | 5 / 2 = 2 | 5 / 2 = 2 | 5 / 2 = 2.5 | 5 / 2 = 2.5 |
See also Data interview questions.