Sub topic 8
Loading Related Data
Assume you know basic INSERT statements and have already created the authors, books, book_authors, and readings tables from earlier chapters. This chapter shows how to load rows that depend on one another. The key idea is to insert parent rows first, use their generated keys, and then insert the related rows.
Why insertion order matters
A foreign key is a column that must refer to an existing row in another table. For example, book_authors.book_id refers to books.book_id. PostgreSQL rejects a link if the referenced book does not exist.
An identity column generates a key when you insert a row. The RETURNING clause gives that generated value back immediately.
INSERT INTO books (title, isbn13, published_year, page_count)
VALUES ('Example Title', '9780000000001', 2001, 320)
RETURNING book_id;You can copy the returned book_id into a later statement, but copying values manually is error-prone. PostgreSQL can pass the value directly between statements with a data-modifying common table expression, or CTE.
Insert related rows with a data-modifying CTE
The following statement creates an author, creates a book, and connects them in book_authors.
WITH new_book AS (
INSERT INTO books (title, isbn13, published_year, page_count)
VALUES ('Example Title', '9780000000001', 2001, 320)
RETURNING book_id
), new_author AS (
INSERT INTO authors (name)
VALUES ('Example Author')
RETURNING author_id
)
INSERT INTO book_authors (book_id, author_id, author_position)
SELECT book_id, author_id, 1
FROM new_book, new_author;Each CTE contains an INSERT. Its RETURNING clause exposes the generated key as a temporary result. The final INSERT combines those results and creates the relationship.
This statement is atomic. If any insert fails, PostgreSQL does not keep only the successful parts. The whole statement fails.
The data flow is:
Group several changes in a transaction
A transaction groups multiple SQL statements into one all-or-nothing operation. BEGIN starts it, COMMIT saves every change, and ROLLBACK discards changes made since BEGIN.
BEGIN;
INSERT INTO books (title, isbn13)
VALUES ('Another Example', '9780000000002');
INSERT INTO readings (book_id)
SELECT book_id
FROM books
WHERE isbn13 = '9780000000002';
COMMIT;The UNIQUE constraint on isbn13 can make the first insert fail. If that happens, the transaction enters an aborted state. Issue ROLLBACK before attempting other work in the same session.
BEGIN;
INSERT INTO books (title, isbn13)
VALUES ('Temporary Book', '9780000000003');
INSERT INTO readings (book_id)
SELECT book_id
FROM books
WHERE isbn13 = '9780000000003';
ROLLBACK;After ROLLBACK, neither the book nor its reading entry remains.
Exercise
Why does the CTE example use RETURNING instead of guessing the next bookid or authorid?
Show answer
Identity values are generated by PostgreSQL and may have gaps or concurrent inserts. RETURNING obtains the exact keys created by the current statement.