The sentence that says what a show in 8 chapters
Goal: answer 4 questions about 100,000 users, writing no step of how
1 of 8 Your guess
Before we start
Apps that save things, a sign-up form, a bank balance, a list of past orders, keep them in a database. You want one answer out of one: the names of everyone in the toy department.
Which picture is closest to how you get that answer?
Pick the closest. You find out which fits at the end.
- SELECT NAMEthe names
- FROM EMPof employees
- WHERE DEPT = 'TOY'in the toy department
1974 − 4 = 1970: the lesson puts Codd's tables four years before the paper
- 1Who are users 1 to 5, and where do they live?not yet
- 2Which accounts belong to each of users 1 to 6?not yet
- 3How many users live in each city?not yet
- 4Users in Pune, or not in Pune: is that everyone?not yet
users 100,000 rows · accounts 106,667 rows · the same rows on every machine
2 of 8 The problem
May 1974: a language for accountants
In 1970 Edgar Codd, at IBM, proposed keeping data as plain grids. The picture is one: employees, with each one's name and department.
The grid is a table, and this one is called EMP. Each line across is a row, one employee. Each line down is a column, one field of every row: NAME, or DEPT, the department.
IBM's lab in San Jose started building a database on Codd's tables. What it lacked was a way for people to ask it things.
Take one question: the names of employees in the toy department. By hand, a person "might look down the DEPT column of the EMP table, finding 'TOY' entries and making a list of the corresponding NAME entries".
Watch the finger: every row is looked at, one at a time. Replay runs it again.
In May 1974, at a workshop in Ann Arbor, Michigan, two IBM researchers, Donald Chamberlin and Raymond Boyce, showed another way. Their first try, SQUARE, looked like a maths formula and was hard to type. So they started again, in words.
Three short lines, each beside what it means. The sentence names the answer and stops. It never says to look down a column or keep a list.
Their language was SEQUEL: a Structured English Query Language.
Their paper says who it was for: people who are "not computer specialists", "accountants, engineers, architects, and urban planners".
Boyce did not see what came of it. He died of an aneurysm in June 1974, a month after the workshop, aged 27. SEQUEL later became SQL, the language nearly every database since has spoken, including Postgres, a free database.
This lesson's practice database is a small Postgres with two tables: users, 100,000 rows, and accounts, 106,667 rows. A script fills it with the same rows on every machine.
Your goal: answer these four questions by writing only what you want, and not one step of how.
- FROM userswhich table
- FROM userswhich table
- WHERE id <= 5which rows count
- FROM userswhich table
- WHERE id <= 5which rows count
- SELECT id, name, citywhich columns you want
- FROM userswhich table
- WHERE city = 'Pune'which rows count
- SELECT id, name, citywhich columns you want
3 of 8 The idea
Say what: three clauses
Question 1: who are users 1 to 5, and where do they live?
Start by naming the table. In SQL each part of a question is a clause, and the first one the database reads is FROM users.
users has five columns: id, name, email, city, signed_up_at. Each user's id is their number, 1 to 100,000. The first five rows are drawn.
Next, which rows count: WHERE id <= 5. The sign <= means "at most".
Every row is checked against it, and only the rows where it comes out true stay. The 5 drawn rows pass. The other 99,995 are set aside.
Last, which columns: SELECT id, name, city. email and signed_up_at drop out.
Question 1 answered: in a real run, these 5 rows are exactly what the database handed back.
A question written this way is a query. People write it SELECT, FROM, WHERE. The database reads it FROM, WHERE, SELECT, the order you just watched.
Change one clause, WHERE city = 'Pune', and watch the same five rows. Two live in Pune. Across all 100,000 users the lesson's run counted 10,065.
The query never said how to find them: walk all 100,000 rows, or jump straight to the Pune ones. It is like asking a librarian for every book by Ursula Le Guin. You say what. The librarian knows the shelves and picks the way.
- FROM usersthe first table
- JOIN accountsand a second one
- WHERE users.id <= 6users 1 to 6 only
- FROM usersthe first table
- JOIN accountsand a second one
- ON accounts.user_id = users.idwhich pairs match
- WHERE users.id <= 6users 1 to 6 only
- FROM usersthe first table
- JOIN accountsand a second one
- ON accounts.user_id = users.idwhich pairs match
- WHERE users.id <= 6users 1 to 6 only
- SELECT id, name, kind, balancethe columns
- FROM usersthe first table
- LEFT JOIN accountsand keep every user
- ON accounts.user_id = users.idwhich pairs match
- WHERE users.id <= 6users 1 to 6 only
- SELECT id, name, kind, balancethe columns
4 of 8 The idea
Two tables, one answer
Question 2: which accounts belong to each of users 1 to 6?
Accounts live in a second table, accounts, 106,667 rows. Each account row carries a user_id: the id of the user who owns it, like a borrowing slip carrying a reader's card number.
Pair them: for each user, find every account whose user_id equals that user's id. That is the ON clause.
Press Play to pair users 1 to 6, one user at a time.
Each pair becomes one row of the answer. Matching rows of two tables on a shared value is a join.
7 rows: user 3 twice, user 6 twice, user 5 not at all. A plain join shows only pairs that exist. Question 2 answered.
Write LEFT JOIN instead and every user from the first table comes back. farid_5 stands next to empty slots where the account would be: 8 rows.
What changed
- Rows back, JOIN to LEFT JOIN: 7 → 8
Why is user 5 alone? The practice data was built so every fifth user has no account: ids 5, 10, 15 and on, 100,000 ÷ 5 = 20,000 users.
Which one you want is part of the answer, so SQL makes you say it.
- FROM userswhich table
- WHERE id <= 5users 1 to 5
- GROUP BY cityone pile per city
- SELECT city, count(*)each pile's city and size
- FROM usersall 100,000
- GROUP BY cityone pile per city
- SELECT city, count(*)each pile's city and size
- ORDER BY count(*) DESCbiggest pile first
10,185 + 10,100 + 10,089 + 10,086 + 10,065+ 9,948 + 9,937 + 9,898 + 9,852 + 9,840 = 100,000
- SELECT count(*)how many rows
- FROM usersall 100,000
- WHERE city = 'Pune' OR city <> 'Pune'Pune, or not Pune: <> means not equal
5 of 8 The problem
Piles, and the blank that is not a value
Question 3: how many users live in each city? That is a question about piles, not rows.
GROUP BY city sorts the rows into one pile per city. count(*) counts the rows in each pile. One row comes out per pile. Here, the five users from before.
Now all 100,000 users. Ten rows came out. ORDER BY count(*) DESC sorts them by count, biggest first: DESC is short for descending.
Nine are cities with roughly ten thousand users each, Delhi on top. The tenth has a count of 9,937 and nothing at all in the city column. Question 3 answered.
In 2009, at a conference in London, the computer scientist Tony Hoare gave a talk called "Null References: The Billion Dollar Mistake". In 1965, designing a programming language, he had added a way for a slot to hold nothing, "simply because it was so easy to implement".
Those 9,937 users signed up without giving a city. Their city is not an empty word: it is a slot marked unknown, drawn here as ?. SQL calls that mark NULL.
Hoare's was a programming language's nothing, not SQL's, but SQL's bites the same way. Next step shows how.
Question 4: users in Pune, or not in Pune. Surely that is everyone?
Is an unknown city Pune? The database will not say yes, and it will not say no. It says unknown, a third answer beside yes and no. SQL calls yes and no true and false, and WHERE keeps only the rows that come out true.
So the whole unknown pile falls out of both halves of the question. The count came back 90,063, not 100,000. Question 4 answered.
What changed
- Users in Pune or not in Pune: 100,000 expected → 90,063 counted
Why not count a blank as not Pune?
Nobody knows it isn't Pune. A librarian holding a book with no author on it would not shelve it with the books not by Le Guin either. She would say she does not know.
The same rule catches city = NULL, which looks like the obvious way to find them. It returned 0 rows: nothing is ever known to equal an unknown, not even another unknown.
SQL has a separate test for the mark itself, IS NULL. It returned all 9,937.
for one user, id 42
Index Scan on users
the jump through the id lookup. Such a lookup is an index.
Nested Loop
for that one user, check each account
for every Pune user
Seq Scan on both tables
read each table in order, end to end
Hash Join
build a lookup of the Pune users in memory, then match each account against it
The names Postgres printed for each route, with EXPLAIN in front of the query
6 of 8 The idea
Who picks the how
Every query so far said what it wanted and left the how alone. Something inside the database decides it, fresh, for every query. That part is the planner, the librarian of this story.
Two queries of the same shape: users joined to their accounts. First for one user, id 42. The planner jumped straight to user 42 through a lookup the table keeps on its ids, then read every account to find user 42's, since this practice database keeps no such lookup on user_id.
Then the same join for every Pune user, about ten thousand of them. This time the planner read both tables from end to end and matched them up.
Same sentence, two routes, and you asked for neither.
Put EXPLAIN in front of a query and Postgres prints the route it picked instead of running it. These are the names it printed for the two routes.
How the planner guesses, and how it guesses wrong, is the planner lesson later in this chapter. Everything between here and there is how rows sit on disk and what makes one route cheaper.
To move the choice yourself: the selectivity crossover lab.
7 of 8 Your guess
Your picture now
Goal met: four questions answered, users 1 to 5, 7 pairs, ten piles, and 90,063 not 100,000, with no step of how written by you. The planner wrote those. Which picture is closest now?
Pick one.
c is SQL. a is the by-hand job the 1974 paper describes: the planner still does steps like it, but it picks them, not you. b would need an answer stored for every question anyone could ask.
8 of 8 Keep this
Keep this
A query names the answer: SELECT the columns, FROM a table, WHERE the rows that count. A join pairs rows on a shared value, GROUP BY folds them into piles, and the planner picks the steps.
The trap: NULL means unknown, and WHERE drops unknown. Ask about everyone and 9,937 users can vanish. Test for it with IS NULL.
Read the full lessonComing up The planner picked a route for every query here. Next, the parts under it: how Postgres keeps rows on disk, caches them in memory and writes each change down before it says done.