Sub topic 8
Loading related data
This chapter covers inserting rows into tables that reference each other. It assumes you have the schema from the earlier chapters: authors, books, book_authors, and readings, with the identity keys and constraints defined there. You should also be comfortable with a basic INSERT.
Why order matters
A foreign key (a column that must match a key in another table) means a child row cannot exist before its parent. You therefore load tables in dependency order. Parents come first, then the join table, then the tables that point at books.
Because the keys are GENERATED ALWAYS AS IDENTITY, you never choose ids yourself. PostgreSQL picks them, and you must ask for them back with RETURNING.
Inserting one row and getting its key
RETURNING makes an INSERT produce a result set, like a SELECT, containing the columns of the row just written.
INSERT INTO authors (name)
VALUES ('Ursula K. Le Guin')
RETURNING author_id;Inserting several rows in one statement is faster than separate statements, because it needs fewer round trips. It is also all-or-nothing:
INSERT INTO authors (name)
VALUES ('N. K. Jemisin'), ('Octavia E. Butler'), ('Ted Chiang')
RETURNING author_id, name;A multi-row INSERT ... RETURNING normally returns rows in the order you listed them. The SQL standard does not guarantee this. When you match returned rows back to your input, match on a value such as name, not on position.
Inserting a book with its authors in one statement
Copying ids by hand between statements is error-prone. A data-modifying CTE (a WITH query whose steps are INSERTs) passes the generated keys from one step to the next inside a single statement.
WITH new_book AS (
INSERT INTO books (title, isbn13, published_year, page_count)
VALUES ('Good Omens', '9780000000010', 1990, 400)
RETURNING book_id
), new_authors AS (
INSERT INTO authors (name)
VALUES ('Terry Pratchett'), ('Neil Gaiman')
RETURNING author_id, name
)
INSERT INTO book_authors (book_id, author_id, author_position)
SELECT nb.book_id,
na.author_id,
CASE na.name WHEN 'Neil Gaiman' THEN 1 ELSE 2 END
FROM new_book nb
CROSS JOIN new_authors na;Three things are worth knowing about this pattern:
- The whole statement is atomic. If the final insert fails, the book and authors are not saved either.
- The steps cannot see each other's rows by querying the tables. They see only what a previous step passes along through
RETURNING. - The foreign keys on
book_authorsare checked at the end of the statement, so referencing rows created in the same statement works.
Each INSERT step in a WITH runs even if the final query never mentions it. Reference a step only when you need its output.
Linking to rows that already exist
The previous example created new authors. More often the author is already in the table, and you must look the id up rather than create a duplicate. The authors.name column is not unique, because two real people can share a name. Looking up by name can therefore return several rows. Use the id when you know it. Otherwise check how many rows a lookup returns before you rely on it.
WITH new_book AS (
INSERT INTO books (title, isbn13, published_year, page_count)
VALUES ('Parable of the Sower', '9780000000027', 1993, 345)
RETURNING book_id
)
INSERT INTO book_authors (book_id, author_id)
SELECT nb.book_id, a.author_id
FROM new_book nb
JOIN authors a ON a.name = 'Octavia E. Butler';If the name matches nothing, the final SELECT returns zero rows. The book is still inserted, with no author link, and PostgreSQL reports no error. Check the row count the client reports, which is INSERT 0 1 in psql. It should equal the number of links you expected.
Inserting from a SELECT also lets you create reading entries for existing books. The explicit casts keep the literal types unambiguous:
INSERT INTO readings (book_id, status, started_on)
SELECT book_id, 'reading'::reading_status, DATE '2026-11-01'
FROM books
WHERE isbn13 = '9780000000027';Here finished_on and rating take their default of NULL. The CHECK (rating IS NULL OR status = 'finished') constraint accepts this row, because no rating was given.
What bad loads look like
The constraints from earlier chapters reject bad data at insert time. Reading the error text tells you which rule fired.
| Cause | Error text (abridged) | Fix |
|---|---|---|
| ISBN has 12 digits | `new row for relation "books" violates check constraint "books_isbn13_check"` | Correct the value |
| Same ISBN loaded twice | `duplicate key value violates unique constraint "books_isbn13_key"` | Skip it, or use an upsert |
| `book_id` does not exist | `insert or update on table "readings" violates foreign key constraint "readings_book_id_fkey"` | Insert the parent first |
| Supplying your own id | `cannot insert a non-DEFAULT value into column "book_id"` | Omit the column |
| Rating on an unfinished book | `new row for relation "readings" violates check constraint "readings_check"` | Set status to `finished` or drop the rating |
Table-level checks get generic names such as readings_check. The error's DETAIL line shows the rejected row, which usually identifies the problem faster than the constraint name does.
A failed statement changes nothing. In a multi-row INSERT, one bad row discards every row in that statement.
Loading rows that already have ids
Sometimes you import data from another system and must keep its ids. GENERATED ALWAYS refuses explicit values unless you say so:
INSERT INTO authors (author_id, name)
OVERRIDING SYSTEM VALUE
VALUES (1000, 'Imported Author');This does not advance the identity sequence. The next normal insert will eventually generate 1000 and fail with a duplicate key error. After an import, move the sequence past the highest id:
SELECT setval(
pg_get_serial_sequence('authors', 'author_id'),
(SELECT max(author_id) FROM authors)
);Bulk loading
For hundreds of rows, a multi-row INSERT is fine. For thousands, use COPY, or \copy in psql, which reads a file on your machine. A common approach is to copy the file into a temporary staging table with plain text columns. You then validate it and run INSERT ... SELECT into the real tables:
CREATE TEMP TABLE staging_books (
title text,
isbn13 text,
published_year text,
page_count text
);
-- In psql: \copy staging_books FROM 'books.csv' WITH (FORMAT csv, HEADER true)
INSERT INTO books (title, isbn13, published_year, page_count)
SELECT title, isbn13, published_year::smallint, page_count::integer
FROM staging_books;The staging table has no constraints, so every row loads. You can then find bad ones, for example with WHERE isbn13 !~ '^[0-9]{13}$', and fix them before they reach the real tables.
Summary of habits
- Insert parents before children.
- Use
RETURNINGand CTEs, not hand-copied ids. - Match returned rows by value, not position.
- Check the reported row count after joins that may match nothing.
- Let constraints reject bad data. Fix the data, not the constraints.
Exercise
You run an INSERT INTO book_authors (book_id, author_id) SELECT nb.book_id, a.author_id FROM new_book nb JOIN authors a ON a.name = 'Octavia Butler' as the last step of a CTE. The real name is stored as 'Octavia E. Butler'. psql reports no error. What happened to the link, and how would you notice?
Show answer
The join matches no authors, so the final SELECT returns zero rows and nothing is inserted into bookauthors. The newbook step still ran, so the book exists with no author. psql reports INSERT 0 0 instead of INSERT 0 1, so comparing the row count with the expected number of links reveals it. Looking up by the author's id, or checking the count of rows linked to the book afterwards, avoids the silent miss.
Exercise
After importing authors with OVERRIDING SYSTEM VALUE and ids up to 1000, a normal INSERT INTO authors (name) works for a while and then fails with a duplicate key error. Why, and what do you run to fix it?
Show answer
The identity sequence was never advanced by the import, so it eventually generates ids that already exist. Run SELECT setval(pg_get_serial_sequence('authors', 'author_id'), (SELECT max(author_id) FROM authors)); so the next generated id is higher than every existing one.