T11 SQL · Lesson 5
Joins
Split facts across tables so that each is written once, link the tables with keys, and lay them side by side again with joins: JOIN for the rows that match, LEFT JOIN to keep the rows that do not, CROSS JOIN for every pairing, short table names with AS, and UNION to stack the answers of two queries.
- explain why facts are split across tables, linked by a primary key and a column that points at it
- join two tables with JOIN ... ON, and name their columns without ambiguity
- keep the rows with no match with LEFT JOIN, and find them with IS NULL
- pair every row of one table with every row of another with CROSS JOIN
- give tables short names with AS
- stack the answers of two queries with UNION and UNION ALL
The back cover
A school keeps its students in one register and its classes in another. A student's line does not copy out the class teacher's name and room; it says 9B, and 9B's line says the rest. When the teacher changes rooms, one line changes.
These pages build a database that way: each fact written once, in its own table, and tables pointing at each other's rows by number. Then they put the pieces back together for every question. JOIN lays two tables side by side, LEFT JOIN keeps the rows that found no partner, CROSS JOIN makes every pairing, and UNION stacks two answers into one.
Before you start
The story: A second page
The Registrar has ruled a fresh page of the ledger for the halls. Each hall gets one line: a number, its name and its keeper. The Engine Hall is 1, the Clock Tower 2, the Couriers' Yard 3, and the Archive 4, though no gauge stands in the Archive yet.
On the gauges' page, every long hall name is struck out and replaced by the hall's number. A new gauge, a compass, arrived this morning, and its hall number is left blank. A clerk grumbles that finding the boiler's keeper now takes two pages instead of one.
Registrar Nadia Folio taps the number beside the boiler. "Ask the ledger, not your memory," she says. "A number that points at a line is a promise, and the ledger can follow it for you. Write each fact once, and ask the ledger to lay the pages side by side."
Every query so far has read one table. Real databases hold many tables, each about one kind of thing: customers, orders, products, payments. The answers people want usually need several of them at once: which customer placed this order, and what did it contain?
This lesson splits the ledger into two tables and puts them back together. Each fact is written once, and tables point at each other's rows by number, with keys. A JOIN lays two tables side by side, matching rows by those numbers. LEFT JOIN also keeps the rows that have no match, CROSS JOIN pairs every row with every row, and UNION stacks the answers of two queries one above the other.
Here is the new ledger. One file of SQL can hold two queries, and each prints its own table:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT * FROM halls;
SELECT * FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
╭────┬────────────────┬───────────────╮
│ id │ name │ keeper │
╞════╪════════════════╪═══════════════╡
│ 1 │ Engine Hall │ Ines Tappet │
│ 2 │ Clock Tower │ Hakim Verge │
│ 3 │ Couriers' Yard │ Dalia Waybill │
│ 4 │ Archive │ Yusra Hollis │
╰────┴────────────────┴───────────────╯
╭────┬──────────┬─────────┬──────┬─────────╮
│ id │ name │ hall_id │ unit │ reading │
╞════╪══════════╪═════════╪══════╪═════════╡
│ 1 │ boiler │ 1 │ C │ 96.5 │
│ 2 │ pump │ 1 │ bar │ 4.2 │
│ 3 │ fan │ 1 │ rpm │ 1200.0 │
│ 4 │ chimney │ 3 │ C │ NULL │
│ 5 │ pendulum │ 2 │ s │ 2.0 │
│ 6 │ kettle │ 3 │ C │ 88.0 │
│ 7 │ bell │ 2 │ Hz │ 440.0 │
│ 8 │ valve │ 1 │ bar │ 4.2 │
│ 9 │ compass │ NULL │ deg │ 270.0 │
╰────┴──────────┴─────────┴──────┴─────────╯
The gauges are lesson 03's eight and one more, the compass. Their hall column has become hall_id, a number that names a row of halls: the boiler's 1 means the Engine Hall. Notice two loose ends, on purpose: the Archive has a row in halls, but no gauge points at it; and the compass's hall_id is NULL, as it has no hall yet. Both will matter.
This lesson builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| An id: INTEGER PRIMARY KEY numbers each row. | id INTEGER PRIMARY KEY | The key that other tables point at. |
| SELECT, WHERE and ORDER BY. | WHERE name = 'boiler' | They all work on joined tables. |
| AS gives a column a name. | reading * 2 AS doubled | Short names for tables. |
| NULL means not known, and IS NULL finds it. | WHERE reading IS NULL | Rows with no match. |
| COUNT(column) skips NULL. | COUNT(reading) is 7 | Counting with LEFT JOIN. |
| GROUP BY gives one answer per group. | GROUP BY hall | Totals per hall, across two tables. |
| DISTINCT drops repeated rows. | SELECT DISTINCT unit | UNION drops them too. |
| An object that points at another by its id, in JavaScript. | { name: 'boiler', hallId: 1 } | A row that points at another table's row. |
| A loop inside a loop. | for (h of halls) for (s of shifts) | Every pairing: CROSS JOIN. |
| Two lists joined end to end. | [...a, ...b] | UNION ALL. |
By the end of this lesson you will be able to:
- explain why facts are split across tables, linked by a primary key and a column that points at it;
- join two tables with JOIN ... ON, and name their columns without ambiguity;
- keep the rows with no match with LEFT JOIN, and find them with IS NULL;
- pair every row of one table with every row of another with CROSS JOIN;
- give tables short names with AS;
- stack the answers of two queries with UNION and UNION ALL.
How to follow this lesson
As before, each block is a file of SQL and the command sqlite3 ledger.db < query.sql, and ledger.db now holds the two tables above. Keep them in view: every join is easiest to check against them, row by row.
Every block was also run with the real sqlite3 3.54.1 in a real terminal, and printed exactly what you see.
In one line
Tables point at each other's rows by number, and joins lay them side by side again, matching rows by those numbers.
Two tables, and the keys between them
At a glance
A database writes each fact once, in the table it describes, and links the tables with numbers.
Each row of a table has a primary key, such as halls.id: a number no other row shares. Another table points at that row by holding the same number in a column of its own, such as gauges.hall_id, called a foreign key. REFERENCES in CREATE TABLE records the link. Change a keeper, and one line changes. In SQLite, the link is only checked when the checks are switched on.
Take a guess: Since when has SQLite checked foreign keys, and why must a program still switch the checks on?
Why split the ledger at all? Picture the old one-table ledger with a keeper column added. The Engine Hall's four gauges would each write Engine Hall and Ines Tappet in full: the same fact, four times. If the keeper changed, four lines would need changing, and a missed one would leave the ledger disagreeing with itself, with no way to tell which line is right.
The cure is to write each fact once, in the table it belongs to. Facts about a hall, its name and its keeper, go in halls, one row per hall. Facts about a gauge go in gauges, and each gauge only says which hall it stands in, by number. Change a keeper, and one line changes.
Primary keys and the columns that point at them
The number that names a row is its table's primary key: halls.id, which lesson 01 made with INTEGER PRIMARY KEY. No two halls share an id, and an id never changes, so it is safe to point at.
A column that holds another table's primary key is called a foreign key, a key from a foreign, other, table. gauges.hall_id is one. Its declaration in the ledger's CREATE TABLE says so in words: hall_id INTEGER REFERENCES halls(id), read aloud as "hall_id refers to the id column of halls".
Follow the boiler's key by hand, with two queries:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT name, hall_id FROM gauges WHERE name = 'boiler';
Terminal: sqlite3 ledger.db < query.sql
╭────────┬─────────╮
│ name │ hall_id │
╞════════╪═════════╡
│ boiler │ 1 │
╰────────┴─────────╯
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT name, keeper FROM halls WHERE id = 1;
Terminal: sqlite3 ledger.db < query.sql
╭─────────────┬─────────────╮
│ name │ keeper │
╞═════════════╪═════════════╡
│ Engine Hall │ Ines Tappet │
╰─────────────┴─────────────╯
The boiler's hall_id is 1, and halls row 1 is the Engine Hall, kept by Ines Tappet. Two lookups for one answer: that is exactly the work a join does for you, for every row at once, in the next section.
| Column | Kind of key | Holds |
|---|---|---|
halls.id | primary key | each hall's own number, never repeated |
gauges.id | primary key | each gauge's own number |
gauges.hall_id | foreign key | the id of the hall the gauge stands in, or NULL |
A promise SQLite does not check by itself
REFERENCES records the link, but SQLite does not check it unless asked. A gauge can point at a hall that does not exist, and nothing complains:
query.sql (ledger.db holds two tables now: halls and gauges)
INSERT INTO gauges (name, hall_id) VALUES ('lamp', 9);
SELECT name, hall_id FROM gauges WHERE name = 'lamp';
Terminal: sqlite3 ledger.db < query.sql
╭──────┬─────────╮
│ name │ hall_id │
╞══════╪═════════╡
│ lamp │ 9 │
╰──────┴─────────╯
There is no hall 9. Turn the checks on, for this connection, with PRAGMA foreign_keys = ON, and the same INSERT is refused:
query.sql (ledger.db holds two tables now: halls and gauges)
PRAGMA foreign_keys = ON;
INSERT INTO gauges (name, hall_id) VALUES ('lamp', 9);
Terminal: sqlite3 ledger.db < query.sql
Error near line 2: FOREIGN KEY constraint failed
"Error near line 2" is the INSERT, refused by the check. Lesson 06 and the PostgreSQL track take keys and their checks further. For reading, which is this lesson's work, the link is what matters.
Worked example 1
Which keeper looks after the kettle? Follow the key by hand.
What we have: The gauges table has the kettle's hall_id; the halls table has each hall's keeper.
What we need: The name of the kettle's hall and its keeper.
The plan: Look up the kettle's hall_id in gauges, then look up that id in halls.
- The kettle's key:
SELECT hall_id FROM gauges WHERE name = 'kettle';. - That hall's row:
SELECT name, keeper FROM halls WHERE id = 3;, with the 3 the first query gave.
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT hall_id FROM gauges WHERE name = 'kettle';
SELECT name, keeper FROM halls WHERE id = 3;
Terminal: sqlite3 ledger.db < query.sql
╭─────────╮
│ hall_id │
╞═════════╡
│ 3 │
╰─────────╯
╭────────────────┬───────────────╮
│ name │ keeper │
╞════════════════╪═══════════════╡
│ Couriers' Yard │ Dalia Waybill │
╰────────────────┴───────────────╯
The kettle stands in the Couriers' Yard, kept by Dalia Waybill.
Check: Look back at the two tables in Before you start: the kettle's row says 3, and halls row 3 is the Couriers' Yard.
A path that fails: Looking for the keeper in gauges, as in SELECT keeper FROM gauges WHERE name = 'kettle';. The keeper is a fact about the hall, so it lives only in halls, and SQLite reports no such column: keeper.
When you are stuck: keys
If you are unsure which table a fact belongs in, ask what it describes. A keeper describes a hall, so it goes in halls.
If you are unsure which column points where, read the REFERENCES in the CREATE TABLE: hall_id refers to halls(id).
A common mistake
Thinking REFERENCES stops bad links by itself. In SQLite it is checked only after PRAGMA foreign_keys = ON.
Your turn
Which hall does the bell stand in? Follow its hall_id by hand.Tap to reveal
- The bell's hall_id, then that row of halls.
Its hall_id is 2, and halls row 2 is the Clock Tower, kept by Hakim Verge.
Why does the halls table hold the keeper, and not the gauges table?Tap to reveal
- How many times would each keeper be written?
A keeper is a fact about a hall. In halls it is written once; in gauges it would be repeated on every gauge of that hall.
What is gauges.hall_id called, and what does it hold?Tap to reveal
- A key from another table.
A foreign key: it holds the id of a row in halls.
Did you know?
Checks you must switch on
SQLite has understood foreign keys for a long time. Its documentation describes the support for foreign key constraints introduced in version 3.6.19, on 2009-10-14. Yet the checks are disabled by default, for compatibility with older programs, and a program must switch them on with PRAGMA foreign_keys for every connection it opens.
Why it fits here: It answers the topic's question, and explains why this lesson's lamp with hall 9 was accepted until the checks were switched on.
Source: SQLite: Foreign Key Support
Parent and child tables
SQLite's documentation names the two sides of a link. The parent table is the table that the foreign key refers to: here, halls. The child table holds the REFERENCES clause: here, gauges. It admits that some books call the parent the referenced table, which is arguably more correct, but tends to lead to confusion.
Why it fits here: It gives this topic's two tables the names the documentation uses: halls is the parent, gauges the child.
Source: SQLite: Foreign Key Support
In one line
Write each fact once, in the table it describes; a primary key such as halls.id names each row, and a foreign key such as gauges.hall_id points at it.
Side by side: JOIN
At a glance
JOIN lays two tables side by side, and ON says which rows belong together.
For each gauge, SQLite finds the halls whose id equals its hall_id, and makes one answer row from each pair. Rows with no partner are left out: the compass, whose hall_id is NULL, and the Archive, which no gauge points at. Columns with the same name in both tables must carry their table's name, such as halls.name, and AS gives tables short names, such as g and h.
Take a guess: Is there a limit to how many tables one join can hold?
A JOIN lays two tables side by side and keeps the pairs of rows that match. ON says what matching means: here, that the gauge's hall_id equals the hall's id.
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT gauges.name, halls.name FROM gauges JOIN halls ON gauges.hall_id = halls.id;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬────────────────╮
│ name │ name │
╞══════════╪════════════════╡
│ boiler │ Engine Hall │
│ pump │ Engine Hall │
│ fan │ Engine Hall │
│ chimney │ Couriers' Yard │
│ pendulum │ Clock Tower │
│ kettle │ Couriers' Yard │
│ bell │ Clock Tower │
│ valve │ Engine Hall │
╰──────────┴────────────────╯
Read it aloud: "the gauge's name and the hall's name, from gauges joined to halls, on the gauge's hall_id being the hall's id." Each gauge found its hall, and the two lookups of the last section happened for every row at once.
Picture it as SQLite does. For each gauge, it looks through halls for every row whose id equals that gauge's hall_id, and makes one answer row from each pair it finds. The boiler, with hall_id 1, pairs with the Engine Hall. Count the answer's rows: eight, not nine. The compass has hall_id NULL, and NULL = 1 is not true, nor NULL = anything, so the compass paired with nothing and was left out. The Archive was left out too, as no gauge points at it.
This kind of join, which keeps only the pairs that match, is called an inner join, and INNER JOIN is its full name. JOIN alone means the same.
Two columns called name
Both tables have a column called name, and another called id. Inside a join, a bare name is ambiguous: SQLite cannot tell which table's column you mean.
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT name, name FROM gauges JOIN halls ON gauges.hall_id = halls.id;
Terminal: sqlite3 ledger.db < query.sql
Parse error near line 1: ambiguous column name: name
SELECT name, name FROM gauges JOIN halls ON gauges.hall_id = halls.id;
^--- error here
The cure is the table's name and a dot before the column, as in the first block: gauges.name and halls.name. A column that only one table has, such as keeper or hall_id, needs no table name, but adding it makes a join easier to read.
Short names for tables: AS
Writing gauges. and halls. before every column grows tiring. AS gives a table a short name for one query, as it gave columns new names in lesson 02. Here g stands for gauges and h for halls, and the columns get clear titles too:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT g.name AS gauge, h.name AS hall, h.keeper
FROM gauges AS g JOIN halls AS h ON g.hall_id = h.id
ORDER BY h.name, g.name;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬────────────────┬───────────────╮
│ gauge │ hall │ keeper │
╞══════════╪════════════════╪═══════════════╡
│ bell │ Clock Tower │ Hakim Verge │
│ pendulum │ Clock Tower │ Hakim Verge │
│ chimney │ Couriers' Yard │ Dalia Waybill │
│ kettle │ Couriers' Yard │ Dalia Waybill │
│ boiler │ Engine Hall │ Ines Tappet │
│ fan │ Engine Hall │ Ines Tappet │
│ pump │ Engine Hall │ Ines Tappet │
│ valve │ Engine Hall │ Ines Tappet │
╰──────────┴────────────────┴───────────────╯
The short names belong to this query alone; the tables keep their real names. The word AS may also be left out, as in FROM gauges g, and you will often see it written that way.
Everything else still works
A join's answer is a table like any other, so WHERE, GROUP BY, ORDER BY and LIMIT all work on it, and they can use the columns of either table. Which gauges does Hakim Verge look after? The name is in halls, the gauges are in gauges:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT g.name FROM gauges g JOIN halls h ON g.hall_id = h.id WHERE h.keeper = 'Hakim Verge' ORDER BY g.name;
Terminal: sqlite3 ledger.db < query.sql
╭──────────╮
│ name │
╞══════════╡
│ bell │
│ pendulum │
╰──────────╯
And lesson 04's averages per hall, now grouped by the hall's name from the other table:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT h.name AS hall, ROUND(AVG(g.reading), 1) AS average FROM gauges g JOIN halls h ON g.hall_id = h.id GROUP BY h.name ORDER BY average DESC;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬─────────╮
│ hall │ average │
╞════════════════╪═════════╡
│ Engine Hall │ 326.2 │
│ Clock Tower │ 221.0 │
│ Couriers' Yard │ 88.0 │
╰────────────────┴─────────╯
Worked example 2
List the gauges measured in C with the hall each stands in, sorted by gauge.
What we have: The unit is in gauges; the hall's name is in halls; hall_id links them.
What we need: One row per gauge in C: its name and its hall's name.
The plan: Join gauges to halls on hall_id = id, keep the rows in C with WHERE, and sort by the gauge's name.
- The join:
FROM gauges g JOIN halls h ON g.hall_id = h.id. - The rows in C:
WHERE g.unit = 'C'. - Both names, each with its table:
SELECT g.name, h.name, sorted withORDER BY g.name.
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT g.name, h.name FROM gauges g JOIN halls h ON g.hall_id = h.id WHERE g.unit = 'C' ORDER BY g.name;
Terminal: sqlite3 ledger.db < query.sql
╭─────────┬────────────────╮
│ name │ name │
╞═════════╪════════════════╡
│ boiler │ Engine Hall │
│ chimney │ Couriers' Yard │
│ kettle │ Couriers' Yard │
╰─────────┴────────────────╯
The boiler in the Engine Hall, and the chimney and the kettle in the Couriers' Yard.
Check: Lesson 04 found three gauges in C: the boiler, the chimney and the kettle. All three have a hall, so the join keeps all three.
A path that fails: Writing SELECT name, name ... without the table names. Both tables have a name column, and SQLite stops with ambiguous column name: name.
Worked example 3
How many gauges does each keeper look after? Most first, and keepers with equal counts by name.
What we have: Keepers are in halls; the gauges point at halls by hall_id.
What we need: One row per keeper with gauges: the keeper and a count.
The plan: Join the tables, group by the keeper, count each group, and sort by the count, then the keeper.
- The join:
FROM halls h JOIN gauges g ON g.hall_id = h.id; the order of the two tables does not matter in an inner join. - One group per keeper:
GROUP BY h.keeper, withCOUNT(*) AS gauges. - Most first, ties by name:
ORDER BY gauges DESC, h.keeper.
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT h.keeper, COUNT(*) AS gauges FROM halls h JOIN gauges g ON g.hall_id = h.id GROUP BY h.keeper ORDER BY gauges DESC, h.keeper;
Terminal: sqlite3 ledger.db < query.sql
╭───────────────┬────────╮
│ keeper │ gauges │
╞═══════════════╪════════╡
│ Ines Tappet │ 4 │
│ Dalia Waybill │ 2 │
│ Hakim Verge │ 2 │
╰───────────────┴────────╯
Ines Tappet 4; Dalia Waybill 2; Hakim Verge 2.
Check: The counts add up to 8, the joined rows: the compass has no hall, so no keeper. Yusra Hollis is missing, as the Archive has no gauges; the next section brings such rows back.
A path that fails: Expecting Yusra Hollis with 0. An inner join keeps only matching pairs, and the Archive matches no gauge, so it never reaches the GROUP BY.
When you are stuck: JOIN
If a join gives too few rows, look for rows with no match, such as a NULL in the column you join on: an inner join drops them.
If SQLite says ambiguous column name, put the table's name or short name and a dot before that column.
A common mistake
Forgetting that an inner join drops unmatched rows. The compass and the Archive are not in any inner join's answer, and no warning says so.
Your turn
Write a query that lists each gauge in the Clock Tower with its reading, using a join and the hall's name.Tap to reveal
- Join, then WHERE h.name = 'Clock Tower'.
SELECT g.name, g.reading FROM gauges g JOIN halls h ON g.hall_id = h.id WHERE h.name = 'Clock Tower'; gives the pendulum (2.0) and the bell (440.0).
How many rows does gauges JOIN halls ON gauges.hall_id = halls.id give, and why not nine?Tap to reveal
- Which gauge has no hall?
Eight: the compass's hall_id is NULL, which matches no hall.
What does FROM gauges AS g mean?Tap to reveal
- A short name.
In this query, g stands for the gauges table, so g.name means gauges.name.
Did you know?
A join is a loop inside a loop
SQLite's documentation says it implements joins as nested loops. By default the left-most table in FROM forms the outer loop and the right-most the inner one. But SQLite will nest the loops in a different order when that helps it choose better indexes, which is why the order you write an inner join in does not change its answer.
Why it fits here: It shows what this topic's JOIN does underneath: for each row of one table, a search through the other.
At most 64 tables in one join
SQLite does not support joins of more than 64 tables. Its documentation explains why: the planner keeps track of the tables in a join with bitmaps, one bit per table. It also says the planner is efficient enough that even a large join can be prepared quickly, and the limit cannot be raised.
Why it fits here: It answers the topic's question with SQLite's real limit, and the reason behind the number.
Source: SQLite: Limits In SQLite
In one line
A JOIN with ON lays two tables side by side and keeps only the matching pairs; give each column its table's name, and tables short names with AS.
Keeping the unmatched: LEFT JOIN
At a glance
LEFT JOIN keeps every row of the table written before JOIN, matched or not.
Where a row found no partner, the other table's columns are filled with NULL, so the compass appears with no hall, or the Archive with no gauge. Testing the partner's id with IS NULL finds exactly the rows that matched nothing. After a LEFT JOIN, count a column of the other table, not COUNT(*), or an empty group counts its row of NULLs as one. RIGHT JOIN and FULL JOIN keep the other side, or both.
Take a guess: How long has SQLite had RIGHT JOIN and FULL JOIN, which other databases had for decades?
An inner join quietly drops every row that has no partner. Often that is wrong: a list of all gauges should not lose the compass because it has no hall yet. LEFT JOIN keeps every row of the table on its left, the one written before the word JOIN, whether it found a match or not. Where there was no match, the other table's columns are filled with NULL.
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT g.name AS gauge, h.name AS hall
FROM gauges g LEFT JOIN halls h ON g.hall_id = h.id
ORDER BY g.id;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬────────────────╮
│ gauge │ hall │
╞══════════╪════════════════╡
│ boiler │ Engine Hall │
│ pump │ Engine Hall │
│ fan │ Engine Hall │
│ chimney │ Couriers' Yard │
│ pendulum │ Clock Tower │
│ kettle │ Couriers' Yard │
│ bell │ Clock Tower │
│ valve │ Engine Hall │
│ compass │ NULL │
╰──────────┴────────────────╯
Nine rows, one per gauge. The compass is back, with NULL for its hall: the join found no hall, and said so. Its full name is LEFT OUTER JOIN; OUTER is usually left out.
Left means the table before JOIN
Swap the two tables, and the kept rows change. With halls on the left, every hall is kept, and the Archive, which no gauge points at, appears with NULL for its gauge:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT h.name AS hall, g.name AS gauge
FROM halls h LEFT JOIN gauges g ON g.hall_id = h.id
ORDER BY h.id, g.name;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬──────────╮
│ hall │ gauge │
╞════════════════╪══════════╡
│ Engine Hall │ boiler │
│ Engine Hall │ fan │
│ Engine Hall │ pump │
│ Engine Hall │ valve │
│ Clock Tower │ bell │
│ Clock Tower │ pendulum │
│ Couriers' Yard │ chimney │
│ Couriers' Yard │ kettle │
│ Archive │ NULL │
╰────────────────┴──────────╯
This time the compass is gone, as halls is now the table that is kept whole, and the compass is in neither of its rows. So choose the left table by asking: whose rows must all be in the answer?
Finding the rows with no match
A LEFT JOIN with IS NULL finds what is missing. The rows that found no partner are the ones whose partner's columns are NULL. Which gauges have no hall?
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT g.name FROM gauges g LEFT JOIN halls h ON g.hall_id = h.id WHERE h.id IS NULL;
Terminal: sqlite3 ledger.db < query.sql
╭─────────╮
│ name │
╞═════════╡
│ compass │
╰─────────╯
Test the partner's id, not some other column of it: a real row always has an id, so h.id IS NULL is true only where no hall was found.
Counting with a LEFT JOIN
How many gauges does each hall hold, empty halls included? A LEFT JOIN from halls keeps the Archive, and lesson 04's COUNT(column) gives it its 0, because COUNT(g.id) skips the NULL:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT h.name AS hall, COUNT(g.id) AS gauges
FROM halls h LEFT JOIN gauges g ON g.hall_id = h.id
GROUP BY h.id ORDER BY h.name;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬────────╮
│ hall │ gauges │
╞════════════════╪════════╡
│ Archive │ 0 │
│ Clock Tower │ 2 │
│ Couriers' Yard │ 2 │
│ Engine Hall │ 4 │
╰────────────────┴────────╯
Write COUNT(*) instead, and the Archive claims a gauge it does not have. COUNT(*) counts rows, and the LEFT JOIN made one row for the Archive, full of NULLs:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT h.name AS hall, COUNT(*) AS gauges
FROM halls h LEFT JOIN gauges g ON g.hall_id = h.id
GROUP BY h.id ORDER BY h.name;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬────────╮
│ hall │ gauges │
╞════════════════╪════════╡
│ Archive │ 1 │
│ Clock Tower │ 2 │
│ Couriers' Yard │ 2 │
│ Engine Hall │ 4 │
╰────────────────┴────────╯
This is one of the most common mistakes in SQL reports, and it looks perfectly reasonable. With a LEFT JOIN, count a column of the right-hand table, such as its id.
RIGHT JOIN and FULL JOIN
A RIGHT JOIN keeps every row of the table on the right instead, and a FULL JOIN keeps every row of both, with NULLs on whichever side found nothing. SQLite has had them since 2022. Here both loose ends appear at once:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT g.name, h.name
FROM gauges g FULL JOIN halls h ON g.hall_id = h.id
ORDER BY h.id, g.name;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬────────────────╮
│ name │ name │
╞══════════╪════════════════╡
│ compass │ NULL │
│ boiler │ Engine Hall │
│ fan │ Engine Hall │
│ pump │ Engine Hall │
│ valve │ Engine Hall │
│ bell │ Clock Tower │
│ pendulum │ Clock Tower │
│ chimney │ Couriers' Yard │
│ kettle │ Couriers' Yard │
│ NULL │ Archive │
╰──────────┴────────────────╯
The compass, with no hall, came first, as its h.id is NULL and NULL sorts first; the Archive, with no gauge, came last. A RIGHT JOIN can always be written as a LEFT JOIN with the tables swapped, and most people write it that way.
| Join | Keeps | Here |
|---|---|---|
JOIN | only the pairs that match | 8 rows: no compass, no Archive |
gauges LEFT JOIN halls | every gauge | 9 rows: the compass with NULL |
halls LEFT JOIN gauges | every hall | 9 rows: the Archive with NULL |
FULL JOIN | every row of both | 10 rows: both loose ends |
Worked example 4
Which halls have no gauges at all?
What we have: Every hall is in halls; gauges point at halls with hall_id.
What we need: The names of the halls that no gauge points at.
The plan: LEFT JOIN from halls, so that every hall is kept, then keep the rows where no gauge was found: g.id IS NULL.
- Every hall, matched or not:
FROM halls AS h LEFT JOIN gauges AS g ON g.hall_id = h.id. - Only those with no gauge:
WHERE g.id IS NULL.
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT h.name AS hall
FROM halls AS h LEFT JOIN gauges AS g ON g.hall_id = h.id
WHERE g.id IS NULL;
Terminal: sqlite3 ledger.db < query.sql
╭─────────╮
│ hall │
╞═════════╡
│ Archive │
╰─────────╯
The Archive.
Check: The counting block above agrees: the Archive is the only hall with 0 gauges.
A path that fails: Writing an inner JOIN with WHERE g.id IS NULL. An inner join has already dropped every unmatched hall, so nothing is left to find, and the answer is empty.
When you are stuck: LEFT JOIN
If the rows you wanted to keep are missing, check which table is on the left: LEFT JOIN keeps the table written before JOIN.
If an empty group counts 1, you counted rows with COUNT(*); count a column of the right-hand table instead.
A common mistake
Testing the right-hand table in WHERE after a LEFT JOIN, as in halls LEFT JOIN gauges ... WHERE g.unit = 'C'. The halls with no gauge in C have NULL there, so WHERE drops them, the Archive and the Clock Tower vanish, and the LEFT JOIN behaves like an inner join. Put such a test in ON instead.
Your turn
Write a query that lists every hall with its keeper and the number of its gauges in C, 0 included.Tap to reveal
- LEFT JOIN with the unit test inside ON, so that halls are not dropped: ON g.hall_id = h.id AND g.unit = 'C'.
SELECT h.name, h.keeper, COUNT(g.id) FROM halls h LEFT JOIN gauges g ON g.hall_id = h.id AND g.unit = 'C' GROUP BY h.id; gives the Engine Hall 1, the Clock Tower 0, the Couriers' Yard 2 and the Archive 0.
Which table's rows does gauges LEFT JOIN halls always keep?Tap to reveal
- The one before JOIN.
Every row of gauges, so all nine gauges, the compass included.
Why does COUNT(*) give the Archive 1 after a LEFT JOIN from halls?Tap to reveal
- How many rows does the Archive get?
The LEFT JOIN made one row for the Archive, with NULL in every gauge column, and COUNT(*) counts rows. COUNT(g.id) skips the NULL and gives 0.
Did you know?
RIGHT and FULL joins, long overdue
For most of its life SQLite had LEFT JOIN but no RIGHT JOIN or FULL JOIN. Its list of changes for version 3.39.0, released on 2022-06-25, opens with the words: add (long overdue) support for RIGHT and FULL OUTER JOIN. A query that keeps both loose ends, as this lesson's FULL JOIN does, needed a workaround before then.
Why it fits here: It answers the topic's question with the release that brought them, and SQLite's own admission that they were late.
Source: SQLite: Release History
Outer joins keep their order
SQLite's planner may reorder the tables of an inner join freely, because the answer is the same either way. Its documentation says outer joins are different: they are neither commutative nor associative, and hence are never reordered. That is the topic's rule seen from the inside: in a LEFT JOIN, which table comes first changes the answer.
Why it fits here: It explains why swapping the tables of this topic's LEFT JOIN kept the Archive and lost the compass.
In one line
LEFT JOIN keeps every row of the table before JOIN, with NULLs where no match was found; find the unmatched rows with the partner's id IS NULL, and count a right-hand column, not COUNT(*).
Every pairing: CROSS JOIN
At a glance
CROSS JOIN pairs every row of one table with every row of another, and needs no ON.
Four halls and two shifts make eight rounds: the answer's size is always the two sizes multiplied, like a loop inside a loop. The same thing happens by accident when a JOIN forgets its ON. So a join's answer that is suddenly far too large points to a missing ON. The oldest way to write a join, a comma between the tables and the matching test in WHERE, is a cross join underneath.
Take a guess: Who is the pairing of every row with every row named after?
Sometimes every row of one table must meet every row of another. Each hall needs a reading round in the morning and in the evening: four halls, two shifts, eight rounds. A CROSS JOIN makes every pairing, and needs no ON, as there is nothing to match. This block makes a small shifts table first, then pairs it with halls:
query.sql (ledger.db holds two tables now: halls and gauges)
CREATE TABLE shifts (name TEXT);
INSERT INTO shifts VALUES ('morning'), ('evening');
SELECT h.name AS hall, s.name AS shift
FROM halls AS h CROSS JOIN shifts AS s
ORDER BY h.id, s.rowid;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬─────────╮
│ hall │ shift │
╞════════════════╪═════════╡
│ Engine Hall │ morning │
│ Engine Hall │ evening │
│ Clock Tower │ morning │
│ Clock Tower │ evening │
│ Couriers' Yard │ morning │
│ Couriers' Yard │ evening │
│ Archive │ morning │
│ Archive │ evening │
╰────────────────┴─────────╯
Eight rows: 4 × 2. A cross join is a loop inside a loop: for each hall, for each shift, one row. The answer's size is always the two tables' sizes multiplied, which is why a cross join of two big tables can be enormous. (s.rowid is the hidden row number of lesson 01, here keeping the shifts in the order they were written.)
The join that forgot its ON
A cross join is also what you get by accident. Leave out the ON of a JOIN, and SQLite has no rule for matching, so it pairs every gauge with every hall:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT COUNT(*) FROM gauges JOIN halls;
Terminal: sqlite3 ledger.db < query.sql
╭──────────╮
│ COUNT(*) │
╞══════════╡
│ 36 │
╰──────────╯
36 rows, 9 gauges × 4 halls, with the boiler paired with the Archive and the compass with every hall. No error is reported: SQLite reads a JOIN without ON as a cross join. Put the ON back, and the count is the real one:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT COUNT(*) FROM gauges JOIN halls ON gauges.hall_id = halls.id;
Terminal: sqlite3 ledger.db < query.sql
╭──────────╮
│ COUNT(*) │
╞══════════╡
│ 8 │
╰──────────╯
So when a join's answer is suddenly far too large, look for a missing or wrong ON first.
The older way to write a join
You will meet joins written with a comma between the tables and the matching test in WHERE. It is the oldest form, and it still works:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT g.name, h.name FROM gauges g, halls h WHERE g.hall_id = h.id AND h.id = 2;
Terminal: sqlite3 ledger.db < query.sql
╭──────────┬─────────────╮
│ name │ name │
╞══════════╪═════════════╡
│ pendulum │ Clock Tower │
│ bell │ Clock Tower │
╰──────────┴─────────────╯
The comma is a cross join, and the WHERE then keeps the matching pairs, so the answer is an inner join's. Its danger is the same as a forgotten ON: drop the matching test from a long WHERE, and the cross join comes back. JOIN ... ON keeps the matching rule next to the tables it joins, which is why it is preferred.
| You write | SQLite makes |
|---|---|
a CROSS JOIN b | every pairing: rows of a × rows of b |
a JOIN b | the same, with no ON to match on |
a JOIN b ON a.x = b.id | only the matching pairs |
a, b WHERE a.x = b.id | the matching pairs, the older way |
Worked example 5
A roster pairs every gauge with every shift. How many rows will it have? Work it out, then let SQLite count.
What we have: 9 gauges, the compass included, and the 2 shifts of the roster.
What we need: The number of rows of gauges CROSS JOIN shifts.
The plan: A cross join's size is the two sizes multiplied. Make the shifts table, then COUNT(*) the cross join.
- By hand: 9 × 2 = 18.
- The shifts:
CREATE TABLE shifts (name TEXT);and an INSERT of morning and evening. - The count:
SELECT COUNT(*) FROM gauges CROSS JOIN shifts;.
query.sql (ledger.db holds two tables now: halls and gauges)
CREATE TABLE shifts (name TEXT);
INSERT INTO shifts VALUES ('morning'), ('evening');
SELECT COUNT(*) FROM gauges CROSS JOIN shifts;
Terminal: sqlite3 ledger.db < query.sql
╭──────────╮
│ COUNT(*) │
╞══════════╡
│ 18 │
╰──────────╯
18 rows.
Check: The compass counts too: a cross join does not match anything, so a NULL hall_id does not matter.
A path that fails: Adding ON gauges.hall_id = shifts.rowid out of habit. That matches gauges to shifts by an unrelated number, which is not what a roster means, and gives a few meaningless pairs instead of 18.
When you are stuck: CROSS JOIN
If a join's answer is far too large, count it and compare with the two tables' sizes multiplied: a match means the ON is missing or always true.
If you mean every pairing, write CROSS JOIN, so that a reader knows the missing ON is on purpose.
A common mistake
Writing JOIN without ON and expecting matched rows. SQLite pairs every row with every row, with no warning.
Your turn
How many rows does halls CROSS JOIN halls give?Tap to reveal
- 4 halls, paired with 4 halls.
16: every hall with every hall, itself included.
What is the difference between a, b WHERE a.x = b.id and a JOIN b ON a.x = b.id?Tap to reveal
- Compare the answers, then the writing.
They give the same rows; the second keeps the matching rule beside the join, so it is harder to lose.
Why does the compass appear in a cross join but not in an inner join?Tap to reveal
- Does a cross join match anything?
A cross join pairs every row without testing anything, while an inner join needs hall_id to match an id, and the compass's NULL matches nothing.
Did you know?
Named after Descartes
Every pairing of the rows of two tables is called their Cartesian product. PostgreSQL's documentation uses the name, and gives the size rule: if the tables have N and M rows, the joined table has N * M rows. The name honours René Descartes: the idea came from his way of naming points by coordinates, a pair of numbers.
Why it fits here: It answers the topic's question, and ties the cross join to the grid of coordinates met in school maths.
Sources: PostgreSQL: Table Expressions; Wikipedia: Cartesian product; Wolfram MathWorld: Cartesian Product
CROSS JOIN as a steering wheel
In SQLite, writing CROSS JOIN does more than say every pairing. Its documentation says SQLite treats the CROSS JOIN operator specially, and never reorders the tables in it. That gives a programmer a way to force the order of the nested loops. It helps when SQLite's own choice turns out to be slow.
Why it fits here: It shows an extra job of this topic's CROSS JOIN in SQLite: fixing the order in which the tables are looped over.
In one line
CROSS JOIN pairs every row of one table with every row of another, rows multiplied; a JOIN with no ON does the same by accident, so a far too large answer means a missing ON.
Stacking answers: UNION
At a glance
UNION stacks the answers of two queries, one above the other, where a join sets tables side by side.
Both queries must give the same number of columns, matched by their place, and the titles come from the first. UNION drops repeated rows, as DISTINCT does; UNION ALL keeps every row and does less work. One ORDER BY, written once at the very end, sorts the whole stacked answer. A SELECT with no FROM can add a row that is in no table at all.
Take a guess: Besides stacking two answers, what else can SQL do with two answers of the same shape?
A join puts tables side by side, adding columns. UNION does the other thing: it puts the answers of two queries one above the other, adding rows. Here are the units of the Engine Hall's gauges, then the units of the Couriers' Yard's, stacked with UNION ALL:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT unit FROM gauges WHERE hall_id = 1
UNION ALL
SELECT unit FROM gauges WHERE hall_id = 3;
Terminal: sqlite3 ledger.db < query.sql
╭──────╮
│ unit │
╞══════╡
│ C │
│ bar │
│ rpm │
│ bar │
│ C │
│ C │
╰──────╯
Four units from the Engine Hall (C, bar, rpm, bar), then two from the yard (C, C): six rows, repeats and all. UNION ALL keeps every row of both answers, like joining two lists end to end.
Plain UNION also drops the repeated rows, as DISTINCT did in lesson 02:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT unit FROM gauges WHERE hall_id = 1
UNION
SELECT unit FROM gauges WHERE hall_id = 3;
Terminal: sqlite3 ledger.db < query.sql
╭──────╮
│ unit │
╞══════╡
│ C │
│ bar │
│ rpm │
╰──────╯
Three units, each once. Use UNION when you want a list of different values, and UNION ALL when every row counts, such as rows you will total later. UNION ALL is also less work, as there are no repeats to look for.
The rules of stacking
Rows can only stack if they have the same shape. Both queries must give the same number of columns:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT name FROM halls UNION SELECT name, unit FROM gauges;
Terminal: sqlite3 ledger.db < query.sql
Parse error near line 1: SELECTs to the left and right of UNION do not have the same number of result columns
The columns are matched by their place, first with first, not by their names, and the answer's titles come from the first query. A column of plain text can label where each row came from:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT name, 'hall' AS kind FROM halls
UNION ALL
SELECT name, 'gauge' FROM gauges
ORDER BY kind, name;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬───────╮
│ name │ kind │
╞════════════════╪═══════╡
│ bell │ gauge │
│ boiler │ gauge │
│ chimney │ gauge │
│ compass │ gauge │
│ fan │ gauge │
│ kettle │ gauge │
│ pendulum │ gauge │
│ pump │ gauge │
│ valve │ gauge │
│ Archive │ hall │
│ Clock Tower │ hall │
│ Couriers' Yard │ hall │
│ Engine Hall │ hall │
╰────────────────┴───────╯
One ORDER BY, written once at the very end, sorts the whole stacked answer, and it can use the first query's titles, such as kind. Notice the order of the names: every capital comes before every small letter, so the halls' names would lead if kind did not sort them apart.
A SELECT with no FROM at all gives one row of its own, so UNION can add a row that is in no table. The Registrar adds herself to the keepers:
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT keeper FROM halls UNION SELECT 'Nadia Folio' ORDER BY keeper;
Terminal: sqlite3 ledger.db < query.sql
╭───────────────╮
│ keeper │
╞═══════════════╡
│ Dalia Waybill │
│ Hakim Verge │
│ Ines Tappet │
│ Nadia Folio │
│ Yusra Hollis │
╰───────────────╯
| JOIN | UNION | |
|---|---|---|
| Adds | columns, side by side | rows, one above the other |
| Needs | a rule for matching rows (ON) | the same number of columns |
| Repeated rows | kept | dropped by UNION, kept by UNION ALL |
Worked example 6
List every name in the ledger, halls and gauges together, each once, sorted.
What we have: Names are in halls.name and gauges.name; no hall shares a name with a gauge.
What we need: One column of all thirteen names, sorted.
The plan: Stack the two name columns with UNION, which also drops any repeats, and sort the whole answer once at the end.
- The halls' names:
SELECT name FROM halls. - Stacked on the gauges' names:
UNION SELECT name FROM gauges. - One sort for everything:
ORDER BY name, at the very end.
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT name FROM halls
UNION
SELECT name FROM gauges
ORDER BY name;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────╮
│ name │
╞════════════════╡
│ Archive │
│ Clock Tower │
│ Couriers' Yard │
│ Engine Hall │
│ bell │
│ boiler │
│ chimney │
│ compass │
│ fan │
│ kettle │
│ pendulum │
│ pump │
│ valve │
╰────────────────╯
Thirteen names: the four halls, then the nine gauges, as capitals sort first.
Check: 4 halls + 9 gauges = 13, and no name repeats, so UNION and UNION ALL give the same rows here.
A path that fails: Putting an ORDER BY on the first query too, as in SELECT name FROM halls ORDER BY name UNION .... Only one ORDER BY is allowed, at the very end, and SQLite says so: ORDER BY clause should come after UNION not before.
When you are stuck: UNION
If SQLite says the SELECTs do not have the same number of result columns, count each query's columns and make them equal.
If repeats are missing that you needed, you wrote UNION; write UNION ALL to keep every row.
A common mistake
Expecting UNION to match columns by name. It matches them by place, so two queries listing the same columns in a different order mix them up silently.
Your turn
Write a query that lists the units of the Clock Tower's and the Couriers' Yard's gauges, each unit once.Tap to reveal
- Two queries on hall_id 2 and 3, joined by UNION.
SELECT unit FROM gauges WHERE hall_id = 2 UNION SELECT unit FROM gauges WHERE hall_id = 3; gives three units: C, Hz and s.
How many rows does SELECT name FROM halls UNION ALL SELECT name FROM halls; give?Tap to reveal
- ALL keeps repeats.
8: each of the four halls twice.
What is the difference between a JOIN and a UNION?Tap to reveal
- Columns, or rows?
A JOIN adds columns, matching rows side by side; a UNION adds rows, stacking two answers of the same shape.
Did you know?
INTERSECT and EXCEPT
UNION has two siblings. SQLite's documentation says INTERSECT returns the rows that both answers share, and EXCEPT returns the rows of the left answer that the right one does not have. Like UNION, both remove duplicate rows. So the units used in both the Engine Hall and the Couriers' Yard are one INTERSECT away.
Why it fits here: It answers the topic's question: two answers of the same shape can also be intersected or subtracted.
Source: SQLite: SELECT
500 answers in one stack
A chain of SELECTs joined by UNION, UNION ALL, EXCEPT or INTERSECT is called a compound SELECT, and each SELECT in it a term. SQLite's documentation says the maximum number of terms is set by SQLITE_MAX_COMPOUND_SELECT, which defaults to 500, because such chains are built by a recursive algorithm and the limit keeps its stack small.
Why it fits here: It puts a number on this topic's stacking: one statement can hold up to 500 stacked SELECTs in SQLite.
Source: SQLite: Limits In SQLite
In one line
UNION stacks the answers of two queries of the same number of columns and drops repeats, UNION ALL keeps them, columns match by place, and one ORDER BY at the end sorts the whole answer.
Where it is used
Almost every screen that shows information from a database is a join behind the scenes.
Orders, customers and products
A shop keeps customers in one table, products in another, and orders in a third, each order pointing at a customer and a product by id. The page that shows "your orders" joins all three: the order's date, the product's name and price, the customer's address. Each fact is stored once; the join gathers them for the screen.
Posts and their authors
A social feed stores each post with an author_id, and the users in their own table. Showing a post with its author's name and picture is posts JOIN users ON posts.author_id = users.id. When a user changes their picture, one row changes, and every post shows the new one.
Finding what is missing
LEFT JOIN with IS NULL answers questions about absence: customers who never ordered, products never sold, students who have not handed in the homework. Data checks use it too, to find rows whose key points at nothing, like the compass with no hall.
| On the screen | In the query |
|---|---|
| An order with the customer's name | orders JOIN customers ON orders.customer_id = customers.id |
| Each category with its product count, 0 included | categories LEFT JOIN products ... COUNT(products.id) |
| Customers who never ordered | customers LEFT JOIN orders ... WHERE orders.id IS NULL |
| Every size in every colour | sizes CROSS JOIN colours |
| One list from two sources | SELECT email FROM staff UNION SELECT email FROM customers |
Mistakes and how to find them
Joins fail in the same two ways as everything else: loudly, with an error, or quietly, with an answer that looks right. This file holds four mistakes, two of each kind.
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT name, keeper FROM gauges JOIN halls ON gauges.hall_id = halls.id;
SELECT COUNT(*) FROM gauges JOIN halls;
SELECT name FROM halls UNION SELECT name, unit FROM gauges;
SELECT h.name, COUNT(*) FROM halls h LEFT JOIN gauges g ON g.hall_id = h.id GROUP BY h.id;
Terminal: sqlite3 ledger.db < query.sql
Parse error near line 1: ambiguous column name: name
SELECT name, keeper FROM gauges JOIN halls ON gauges.hall_id = halls.id;
^--- error here
╭──────────╮
│ COUNT(*) │
╞══════════╡
│ 36 │
╰──────────╯
Parse error near line 3: SELECTs to the left and right of UNION do not have the same number of result columns
╭────────────────┬──────────╮
│ name │ COUNT(*) │
╞════════════════╪══════════╡
│ Engine Hall │ 4 │
│ Clock Tower │ 2 │
│ Couriers' Yard │ 2 │
│ Archive │ 1 │
╰────────────────┴──────────╯
Line 1 asked for name, which both tables have. SQLite cannot guess which one, and points at it. Write g.name or h.name.
Line 3 stacked one column on two. UNION needs the same number of columns on both sides, and says so.
Lines 2 and 4 are the quiet ones. Line 2 forgot its ON, and counted 36 pairings of every gauge with every hall instead of the 8 real ones. Line 4 counted rows after a LEFT JOIN, so the Archive, which has no gauges, shows 1: the row of NULLs that the LEFT JOIN made for it. COUNT(g.id) would have given 0.
The quiet mistakes
| The query | What it really does | What was meant |
|---|---|---|
a JOIN b with no ON | pairs every row with every row | a JOIN b ON a.x = b.id |
COUNT(*) after a LEFT JOIN | counts the row of NULLs as one | COUNT(b.id) |
JOIN when every row must stay | drops the rows with no match | LEFT JOIN |
LEFT JOIN b ... WHERE b.col = 'x' | drops the unmatched rows again | put the test in ON |
a LEFT JOIN b with the tables swapped | keeps the wrong table's rows | put the table to keep before JOIN |
UNION when every row counts | drops repeated rows | UNION ALL |
A way to check a join
- Before joining, count each table's rows:
SELECT COUNT(*) FROM gauges;and the same for halls. - Count the join's rows. An inner join can never give more rows than the pairs that match; a count near the two sizes multiplied means a missing ON.
- Look for keys that point at nothing, or at NULL: they vanish from an inner join.
- Switch to LEFT JOIN and look at the rows with NULLs: they are the ones the inner join dropped.
- Show the keys themselves in the SELECT list, such as g.hall_id and h.id, so you can see each match.
The debugging corner: show both keys
Put both sides of the ON in the SELECT list: SELECT g.name, g.hall_id, h.id, h.name FROM gauges g LEFT JOIN halls h ON g.hall_id = h.id; Each row then shows the very numbers that were matched, and a NULL in h.id marks a gauge whose key found nothing.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
query.sql (ledger.db holds two tables now: halls and gauges)
SELECT h.name AS hall, COUNT(g.id) AS gauges
FROM halls AS h LEFT JOIN gauges AS g ON g.hall_id = h.id
GROUP BY h.id
ORDER BY gauges DESC, hall;
Terminal: sqlite3 ledger.db < query.sql
╭────────────────┬────────╮
│ hall │ gauges │
╞════════════════╪════════╡
│ Engine Hall │ 4 │
│ Clock Tower │ 2 │
│ Couriers' Yard │ 2 │
│ Archive │ 0 │
╰────────────────┴────────╯
| To do this | Write this |
|---|---|
| Name a row | id INTEGER PRIMARY KEY, the primary key |
| Point at another table's row | hall_id INTEGER REFERENCES halls(id), a foreign key |
| Check the links | PRAGMA foreign_keys = ON; |
| Matching pairs only | FROM gauges JOIN halls ON gauges.hall_id = halls.id |
| Name a column of one table | gauges.name, halls.name |
| Short names for tables | FROM gauges AS g JOIN halls AS h ON g.hall_id = h.id |
| Keep every row of the left table | halls h LEFT JOIN gauges g ON g.hall_id = h.id |
| Find rows with no match | ... LEFT JOIN ... WHERE g.id IS NULL |
| Count with a LEFT JOIN | COUNT(g.id), not COUNT(*) |
| Every pairing | halls CROSS JOIN shifts |
| Stack two answers, each row once | SELECT ... UNION SELECT ... |
| Stack two answers, every row | SELECT ... UNION ALL SELECT ... |
Words to know: primary key, foreign key, REFERENCES, join, JOIN, ON, inner join, ambiguous column, table alias, LEFT JOIN, RIGHT JOIN, FULL JOIN, CROSS JOIN, UNION, UNION ALL.
Self-check
Say each answer aloud before you open it.
Why are the keepers in their own table instead of on every gauge's row?Tap to reveal
- How often is each fact written?
So that each keeper is written once: a change is one line, and the ledger cannot disagree with itself.
Which rows does an inner join keep, and which does it drop?Tap to reveal
- Think of the compass and the Archive.
It keeps the pairs that match its ON and drops every row with no match, such as the compass and the Archive.
What does LEFT JOIN keep that JOIN does not?Tap to reveal
- The table before JOIN.
Every row of the left table, with NULLs where nothing matched.
What happens to a JOIN with no ON?Tap to reveal
- Nothing to match on.
It pairs every row with every row, like a CROSS JOIN.
What is the difference between UNION and UNION ALL?Tap to reveal
- Repeats.
UNION drops repeated rows; UNION ALL keeps every row.
The story: Two pages, one answer
By evening the clerks ask their questions across both pages. Each gauge stands beside its hall and its keeper. Each hall shows how many gauges it holds, and the Archive shows 0 instead of vanishing. One question finds the gauges with no hall, and finds only the compass.
When the Registrar finds a keeper's name misspelt, she corrects one line on the halls' page, and every answer about that hall's gauges shows the right name at once.
The Registrar closes the ledger. "Two pages, one answer," she says. "Tomorrow we stop only reading the ledger. We write in it: new lines, corrections, and lines struck out."
Reagents gathered: JOIN, ON, LEFT JOIN, CROSS JOIN, AS, UNION.
Sources
- SQLite's documentation (the SQL language, the command-line shell, the file format, the datatypes) (Public domain: all of SQLite's code and documentation (sqlite.org/copyright.html, read 2026-11-21); reused with credit)
- The PostgreSQL documentation (The PostgreSQL Licence, which covers the software and its documentation (its licence page, read 2026-10-26); reused with credit)