Sub topic 6
Books with Several Authors: the Join Table
Assume you know basic SELECT, INSERT, and CREATE TABLE, and that the books and authors tables already exist. This chapter uses PostgreSQL 12 or newer.
A book can have several authors, and an author can write several books. This is a many-to-many relationship. A single foreign-key column in either table cannot represent it cleanly. Instead, create a third table called a join table. Each row in the join table records one book-author relationship.
Define the relationship
The join table stores the primary key from each related table. These columns are foreign keys, which means every referenced book and author must exist.
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)
);The composite primary key contains both book_id and author_id. A composite key is a key made from more than one column. It prevents the same author from being attached to the same book twice.
author_position records the order in which authors should appear. For example, position 1 can identify the first listed author. The database does not automatically prevent two authors from sharing the same position. If your rules require one author per position, add this constraint:
ALTER TABLE book_authors
ADD CONSTRAINT book_authors_position_unique
UNIQUE (book_id, author_position);The two foreign keys have different delete actions:
ON DELETE CASCADEremoves relationship rows when a book is deleted.ON DELETE RESTRICTprevents deleting an author while a relationship still refers to that author.
This protects you from orphaned relationships. An orphan is a row that points to a record that no longer exists.
> callout note > The join table describes a relationship, not a duplicate copy of a book or author. Store each book and author once, then store their connections separately.
Add and inspect relationships
First insert the base rows. The generated identity columns provide their IDs.
INSERT INTO authors (name)
VALUES ('Octavia Butler'), ('Samuel R. Delany');
INSERT INTO books (title)
VALUES ('Kindred'), ('Dhalgren');
INSERT INTO book_authors (book_id, author_id, author_position)
VALUES
(1, 1, 1),
(2, 2, 1);A book with multiple authors needs multiple rows with the same book_id:
INSERT INTO book_authors (book_id, author_id, author_position)
VALUES
(3, 1, 1),
(3, 2, 2);The exact IDs depend on the rows already in your database. In application code, obtain generated IDs with INSERT ... RETURNING rather than assuming that a new row has a particular number.
To list the authors for each book, join through the join table:
SELECT b.title,
string_agg(a.name, ', ' ORDER BY ba.author_position) AS authors
FROM books AS b
JOIN book_authors AS ba USING (book_id)
JOIN authors AS a USING (author_id)
GROUP BY b.book_id, b.title
ORDER BY b.title;string_agg combines several author names into one ordered string. The GROUP BY creates one result row per book.
Exercise
Why does the primary key use both bookid and authorid instead of only book_id?
Show answer
Because one book can have several authors. The pair uniquely identifies one book-author relationship while allowing many rows for the same book.