Sub topic 9
Joining books, authors, and readings
This chapter assumes you can write basic SELECT statements and that the tables from the earlier chapters exist: authors, books, book_authors, and readings. Here you combine them. The focus is on which join type to pick, why rows disappear or multiply, and how to avoid both problems.
Why joins are needed
The schema splits facts across tables so each fact is stored once. A book's title lives in books, the author's name lives in authors, and book_authors links the two. A join rebuilds the combined view at query time. The foreign keys you declared guarantee that every link points at a real row.
Sample data
The examples below use this small data set. Run it once so the outputs match. It includes several awkward cases on purpose: a book with two authors, a book read twice, a book with no author link and no readings, and an author with no books.
INSERT INTO authors (name) VALUES
('Ada Writer'), ('Ben Coauthor'), ('Cleo Solo'), ('Dana Unpublished');
INSERT INTO books (title, isbn13, published_year, page_count) VALUES
('Graph Basics', '9780000000101', 2010, 300),
('Tables and Keys', '9780000000102', 2015, 250),
('Lonely Pages', '9780000000103', 2020, 180),
('Unread Shelf', '9780000000104', 2022, 400);
INSERT INTO book_authors (book_id, author_id, author_position)
SELECT b.book_id, a.author_id, v.pos
FROM (VALUES
('9780000000101', 'Ada Writer', 1),
('9780000000101', 'Ben Coauthor', 2),
('9780000000102', 'Ada Writer', 1),
('9780000000103', 'Cleo Solo', 1)
) AS v(isbn13, name, pos)
JOIN books b ON b.isbn13 = v.isbn13
JOIN authors a ON a.name = v.name;
INSERT INTO readings (book_id, status, started_on, finished_on, rating)
SELECT b.book_id, v.status::reading_status, v.started::date,
v.finished::date, v.rating::smallint
FROM (VALUES
('9780000000101', 'finished', '2023-01-05', '2023-01-20', 5),
('9780000000101', 'finished', '2024-03-01', '2024-03-12', 4),
('9780000000102', 'reading', '2023-06-01', NULL, NULL),
('9780000000103', 'finished', '2023-08-02', '2023-08-09', 3)
) AS v(isbn13, status, started, finished, rating)
JOIN books b ON b.isbn13 = v.isbn13;Inner joins: only matching rows survive
JOIN means INNER JOIN. A row appears in the result only if the join condition finds a match on both sides. Joining through the join table lists each book with its authors:
SELECT b.title,
string_agg(a.name, ', ' ORDER BY ba.author_position) AS authors
FROM books b
JOIN book_authors ba USING (book_id)
JOIN authors a USING (author_id)
GROUP BY b.book_id, b.title
ORDER BY b.title; title | authors
-----------------+--------------------------
Graph Basics | Ada Writer, Ben Coauthor
Lonely Pages | Cleo Solo
Tables and Keys | Ada WriterUnread Shelf is missing. It has no row in book_authors, so the inner join discards it. That is correct behavior, but it surprises people who expect every book in the output.
USING (book_id) is shorthand for ON b.book_id = ba.book_id when both tables name the column the same way. It also merges the two columns into one in the result. When the names differ, or the condition is not a plain equality, write ON.
Outer joins: keep rows that have no match
A LEFT JOIN keeps every row from the left table. Where the right table has no match, its columns come back as NULL.
SELECT b.title, r.status, r.rating
FROM books b
LEFT JOIN readings r USING (book_id)
ORDER BY b.title, r.finished_on; title | status | rating
-----------------+----------+--------
Graph Basics | finished | 5
Graph Basics | finished | 4
Lonely Pages | finished | 3
Tables and Keys | reading |
Unread Shelf | |The two Graph Basics rows are not a mistake. readings.book_id is not unique, so one book can match many readings. That is what lets you log a re-read.
| Join type | Keeps unmatched left rows | Keeps unmatched right rows | Typical use here |
|---|---|---|---|
| `JOIN` (inner) | No | No | Books that have authors |
| `LEFT JOIN` | Yes | No | All books, with readings if any |
| `RIGHT JOIN` | No | Yes | Same as `LEFT JOIN` with the tables swapped |
| `FULL JOIN` | Yes | Yes | Auditing mismatches between two tables |
Most people write only LEFT JOIN and order the tables to suit. It reads more consistently than mixing in RIGHT JOIN.
Finding rows with no match
A left join followed by an IS NULL test on the right table's key is called an anti-join. It answers questions such as "which authors have no books?"
SELECT a.name
FROM authors a
LEFT JOIN book_authors ba USING (author_id)
WHERE ba.author_id IS NULL;This returns Dana Unpublished. The same shape finds books you never started:
SELECT b.title
FROM books b
LEFT JOIN readings r USING (book_id)
WHERE r.reading_id IS NULL;Test a column that can never be NULL in a real row, such as a primary key. Testing a nullable column like rating would also match real rows whose value is NULL. NOT EXISTS expresses the same idea and is equally fast in PostgreSQL:
SELECT b.title
FROM books b
WHERE NOT EXISTS (SELECT 1 FROM readings r WHERE r.book_id = b.book_id);ON versus WHERE in outer joins
A condition's position changes the meaning of a left join. Suppose you want every book, plus its finished readings only.
-- Keeps all books; non-finished readings are simply not matched
SELECT b.title, r.finished_on
FROM books b
LEFT JOIN readings r
ON r.book_id = b.book_id AND r.status = 'finished'
ORDER BY b.title;
-- Drops books with no finished reading, so it behaves like an inner join
SELECT b.title, r.finished_on
FROM books b
LEFT JOIN readings r ON r.book_id = b.book_id
WHERE r.status = 'finished'
ORDER BY b.title;The first query returns all four books. Tables and Keys and Unread Shelf show a NULL date. In the second, WHERE runs after the join. Unmatched rows have r.status equal to NULL, and NULL = 'finished' is not true, so those rows are filtered out.
Row multiplication across two one-to-many paths
The most common join bug is joining one table to two independent many-side tables at once. Each book has authors and readings. Joining both gives every author paired with every reading.
SELECT b.title, count(*) AS rows_returned
FROM books b
JOIN book_authors ba USING (book_id)
JOIN readings r USING (book_id)
GROUP BY b.book_id, b.title
ORDER BY b.title; title | rows_returned
-----------------+---------------
Graph Basics | 4
Lonely Pages | 1
Tables and Keys | 1Graph Basics has two authors and two readings, so the result has 2 × 2 = 4 rows. Any sum(page_count) or count(*) over this result is inflated. Nothing errors, so the wrong number looks plausible.
The fix is to collapse each many-side to one row per book before joining. Do that in subqueries:
SELECT b.title,
coalesce(au.authors, 'unknown') AS authors,
coalesce(rd.times_read, 0) AS times_read,
rd.avg_rating
FROM books b
LEFT JOIN (
SELECT ba.book_id,
string_agg(a.name, ', ' ORDER BY ba.author_position) AS authors
FROM book_authors ba
JOIN authors a USING (author_id)
GROUP BY ba.book_id
) au USING (book_id)
LEFT JOIN (
SELECT book_id,
count(*) FILTER (WHERE status = 'finished') AS times_read,
round(avg(rating), 2) AS avg_rating
FROM readings
GROUP BY book_id
) rd USING (book_id)
ORDER BY b.title; title | authors | times_read | avg_rating
-----------------+--------------------------+------------+------------
Graph Basics | Ada Writer, Ben Coauthor | 2 | 4.50
Lonely Pages | Cleo Solo | 1 | 3.00
Tables and Keys | Ada Writer | 0 |
Unread Shelf | unknown | 0 |Each subquery returns at most one row per book_id, so the joins cannot multiply rows. The outer LEFT JOINs keep all four books. coalesce replaces NULL with a default for display.
Joining a table to itself
You can join a table to itself by giving it two aliases. To list pairs of co-authors, join book_authors to itself on the same book:
SELECT DISTINCT a1.name AS author, a2.name AS coauthor
FROM book_authors x
JOIN book_authors y ON y.book_id = x.book_id AND y.author_id <> x.author_id
JOIN authors a1 ON a1.author_id = x.author_id
JOIN authors a2 ON a2.author_id = y.author_id
ORDER BY author;The <> condition stops an author from matching themselves. With the sample data this returns Ada Writer / Ben Coauthor and Ben Coauthor / Ada Writer.
Common errors
- Ambiguous column. A name that exists in two joined tables, such as
book_idwithoutUSING, raisescolumn reference "book_id" is ambiguous. Qualify it with an alias. - Missing join condition. A
JOINwithoutONorUSINGis a syntax error. Listing tables with commas and forgetting theWHEREcondition produces a cross join, where 1,000 books and 5,000 readings give 5,000,000 rows. GROUP BYmismatch. Every selected column must be grouped or aggregated. Grouping by the primary keyb.book_idlets PostgreSQL accept otherbookscolumns that depend on it.- Wrong count after a left join.
count(*)counts theNULL-filled row for an unmatched book as 1. Usecount(r.reading_id)to count only real matches.
Exercise
Write a query that returns every author's name and the number of books they have in the database, including authors with zero books. Which join type and which count expression do you need?
Show answer
Use a LEFT JOIN from authors to bookauthors and count a column from the right side: SELECT a.name, count(ba.bookid) AS books FROM authors a LEFT JOIN bookauthors ba USING (authorid) GROUP BY a.authorid, a.name ORDER BY a.name; count(ba.bookid) skips NULLs, so Dana Unpublished shows 0 instead of 1, which count(*) would give.
Exercise
A colleague's query joins books to bookauthors and to readings, then reports sum(pagecount) per author. Why are the totals too high for books that were read twice, and how would you fix it?
Show answer
Each reading row repeats the book once per reading, so a book read twice is counted twice in the sum. Fix it by removing readings from the join, since page_count does not need it, or by aggregating readings in a subquery that returns one row per book before joining.