Sub topic 6
Books with several authors: the join table
A book can have several authors, and an author can write several books. This chapter models that with a third table that sits between books and authors. It assumes you have created the authors and books tables from the earlier chapters, and that you know primary keys, foreign keys, and ON DELETE actions.
Why a foreign key on books is not enough
Suppose you put an author_id column on books. Each book can then point to exactly one author. Good Omens has two authors, so the design fails on the first interesting row.
Two common workarounds are also wrong:
- Several columns such as
author1_idandauthor2_id. These fix the maximum number of authors, and every query must check each column. - A list in one column, such as
'1,2'in a text column or an array. PostgreSQL cannot enforce a foreign key on each element, so you lose referential integrity. Finding all books by one author also becomes awkward.
The relational answer is a join table (also called a junction or association table). It has one row per book-author pair. Each side of the relationship stays one-to-many, and the pair of one-to-many links together form a many-to-many relationship.
The join table
CREATE TABLE book_authors (
book_id bigint NOT NULL REFERENCES books (book_id) ON DELETE CASCADE,
author_id bigint NOT NULL REFERENCES authors (author_id) ON DELETE RESTRICT,
author_position smallint NOT NULL DEFAULT 1,
PRIMARY KEY (book_id, author_id)
);Each part does a specific job.
The composite primary key
PRIMARY KEY (book_id, author_id) makes the pair unique, so the same author cannot be linked to the same book twice. It also implies NOT NULL on both columns. The explicit NOT NULL in the column definitions is redundant but harmless, and it documents the intent.
The join table needs no surrogate bigint identity column. The pair already identifies a row. Add a surrogate key only if another table must reference individual link rows, which is not the case here.
PostgreSQL implements the primary key with a unique B-tree index on (book_id, author_id). That has a consequence for performance, covered below.
Two different delete behaviors
The two foreign keys intentionally use different referential actions:
| Foreign key | Action | Effect |
|---|---|---|
| `book_id` to `books` | `ON DELETE CASCADE` | Deleting a book also deletes its author links. |
| `author_id` to `authors` | `ON DELETE RESTRICT` | Deleting an author who still has linked books fails. |
The reasoning is that a link row has no meaning without its book, so it should disappear with the book. Silently removing an author's links because the author row was deleted could leave a book with no authors and hide the mistake. RESTRICT forces you to deal with the links first.
Note that RESTRICT is checked immediately. If you used NO ACTION instead (the default), the check could be deferred to the end of the statement or transaction for a deferrable constraint. For a plain ON DELETE rule on a non-deferrable constraint the visible result is the same, but RESTRICT states the intent clearly.
The author position
Authors on a cover appear in a set order, and a relational table has no inherent row order. The author_position column stores that order, so queries can sort by it. It belongs on the join table because it describes the relationship ("second author of this book") rather than the book or the author alone. Any attribute that describes a pairing, such as a role like editor or translator, goes in this table.
Loading sample data
This script assumes empty authors and books tables, so each name matches one row.
INSERT INTO authors (name)
VALUES ('Terry Pratchett'), ('Neil Gaiman');
INSERT INTO books (title, isbn13, published_year, page_count)
VALUES ('Good Omens', '9780060853983', 1990, 412),
('Neverwhere', '9780060557812', 1996, 400);
INSERT INTO book_authors (book_id, author_id, author_position)
SELECT b.book_id, a.author_id, v.pos
FROM (VALUES ('9780060853983', 'Terry Pratchett', 1),
('9780060853983', 'Neil Gaiman', 2),
('9780060557812', 'Neil Gaiman', 1)) AS v(isbn13, name, pos)
JOIN books b ON b.isbn13 = v.isbn13
JOIN authors a ON a.name = v.name;The last statement looks up the generated identity values by natural keys (ISBN and name) instead of hard-coding ids. Hard-coded ids are fragile because identity values depend on insertion history. The next chapter shows how to create the book, author, and link in a single statement.
What the constraints reject
Try the failure cases deliberately. Each error teaches you which constraint fired.
-- Same pair twice
INSERT INTO book_authors (book_id, author_id)
SELECT book_id, author_id FROM book_authors LIMIT 1;
-- ERROR: duplicate key value violates unique constraint "book_authors_pkey"
-- A book that does not exist
INSERT INTO book_authors (book_id, author_id) VALUES (999999, 1);
-- ERROR: insert or update on table "book_authors" violates foreign key constraint "book_authors_book_id_fkey"
-- Deleting an author who still has books
DELETE FROM authors WHERE name = 'Neil Gaiman';
-- ERROR: update or delete on table "authors" violates foreign key constraint "book_authors_author_id_fkey" on table "book_authors"Constraint names such as book_authors_pkey are generated by PostgreSQL from the table and column names. Your application code can match on them, so name important constraints explicitly if you plan to rely on them.
Querying in both directions
The join table lets you traverse the relationship from either side.
-- All authors of one book, in cover order
SELECT a.name
FROM book_authors ba
JOIN authors a USING (author_id)
JOIN books b USING (book_id)
WHERE b.isbn13 = '9780060853983'
ORDER BY ba.author_position;
-- All books by one author
SELECT b.title
FROM books b
JOIN book_authors ba USING (book_id)
JOIN authors a USING (author_id)
WHERE a.name = 'Neil Gaiman'
ORDER BY b.published_year;The first query runs efficiently because the primary-key index starts with book_id. The second filters by author, and a B-tree index can only be searched efficiently from its leading column. Without another index, PostgreSQL may scan the whole join table. The indexing chapter adds book_authors_author_id_idx to fix this, so remember that a composite key indexes one direction only.
Making positions reliable
As written, nothing stops two authors from sharing position 1 on the same book. If order matters, add a constraint:
ALTER TABLE book_authors
ADD CONSTRAINT book_authors_position_positive CHECK (author_position > 0),
ADD CONSTRAINT book_authors_position_unique
UNIQUE (book_id, author_position)
DEFERRABLE INITIALLY IMMEDIATE;The DEFERRABLE option matters when you reorder authors. Swapping two positions with one UPDATE can briefly produce a duplicate while rows are processed one at a time. A deferrable unique constraint is checked at the end of the statement, so the swap succeeds:
UPDATE book_authors
SET author_position = 3 - author_position
WHERE book_id = (SELECT book_id FROM books WHERE isbn13 = '9780060853983');This update works because 3 - 1 = 2 and 3 - 2 = 1 for a two-author book. For books with more authors you would write a different expression.
Common mistakes
- Using
CASCADEon both foreign keys. Deleting one author would then remove links from many books without warning. - Storing the author name in
book_authors. This duplicates data fromauthorsand lets the two copies disagree. - Expecting an author-first lookup to be fast. The composite primary key serves book-first lookups only.
- Inserting links with hard-coded ids. Resolve ids by natural key, or capture them with
RETURNING. - Forgetting that duplicate names are allowed. Two different people can share a name, so
authors.nameis deliberately not unique. A name-based lookup like the one above is only safe for sample data.
Exercise
A reader wants to record that a book has a translator as well as authors. Where should the role go, and why is a new column on books or authors the wrong place? What change to the primary key would you need if the same person could be both author and translator of the same book?
Show answer
Add a role column to book_authors, because a role describes one person's relationship to one book. A column on books would hold only one value per book, and a column on authors would apply to every book that person is linked to. If the same person can hold two roles on one book, the key (book_id, author_id) would reject the second row, so the primary key must become (book_id, author_id, role).
Exercise
You run DELETE FROM books WHERE book_id = 1; and the book has two rows in book_authors. What happens to those rows and to the author rows, given the foreign keys in this chapter?
Show answer
The two book_authors rows are deleted automatically because of ON DELETE CASCADE on book_id. The authors rows are untouched, because deleting a link row does not affect the authors table.