A join combines rows according to an ON condition. An inner join keeps matching pairs. Table aliases keep qualified column names readable and disambiguate names shared by tables.
SELECT books.title, shelves.label AS shelf
FROM books JOIN shelves ON books.shelf_id = shelves.id
ORDER BY books.id;
The result is Moss Atlas / Nature, River Notes / Nature, and Clay Roads / History. Night Sky has no shelf ID and therefore no matching pair. A single shelf can match several books, so joins can multiply rows. A foreign key describes a constraint; the query still needs an appropriate join condition. Missing or incorrect conditions can produce many unintended pairs.
Here books.title means the title column of books; the dot qualifies the name. The query spells out table names rather than using aliases, but FROM books AS b JOIN shelves AS s ON b.shelf_id = s.id is an equivalent way to name the inputs. JOIN without INNER means an inner join in SQLite. Additional joins can add more tables, each with its own matching condition; check whether each join preserves or removes unmatched rows.
Trace two joins
Use the setup fixture in a fresh database. First add two topics and three associations. These rows are separate from the fixture; run this block once after setup.
CREATE TABLE topics (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE book_topics (book_id INTEGER NOT NULL REFERENCES books(id),
topic_id INTEGER NOT NULL REFERENCES topics(id),
PRIMARY KEY (book_id, topic_id));
INSERT INTO topics VALUES (10, 'Plants'), (20, 'Maps');
INSERT INTO book_topics VALUES (1, 10), (1, 20), (2, 10);
SELECT books.title, topics.name
FROM books JOIN book_topics ON books.id = book_topics.book_id
JOIN topics ON book_topics.topic_id = topics.id
ORDER BY books.id, topics.id;
After the first join, book 1 has two association rows and book 2 has one; books 3 and 4 have no association and disappear. The second join adds each matching topic name:
| title | name |
|---|---|
| Moss Atlas | Plants |
| Moss Atlas | Maps |
| River Notes | Plants |
The repeated title represents two different pairs, not necessarily a duplicate to remove. If the first join were a left join but the second remained an inner join, books without topics would still disappear at the second join. A left join at both steps would retain them with NULL topic values. Each step operates on the intermediate rows.