Sub topic 5
Linking tables with foreign keys
This chapter explains how foreign keys connect the tables of the book-tracking schema and what PostgreSQL does when someone breaks a link. It assumes you know primary keys and identity columns, and NOT NULL, UNIQUE and CHECK constraints, from the earlier chapters. It also assumes the authors, books, book_authors and readings tables already exist. Everything here runs on PostgreSQL 12 or newer, and features that need a newer version are marked.
What a foreign key guarantees
A foreign key is a constraint that ties the values in one table's column (the child) to the values in another table's column (the parent). Every non-NULL value in the child column must exist in the parent column. The database checks this on every INSERT, UPDATE and DELETE that could break it. Application code can't skip the check, and a race between two sessions can't get around it.
The parent column must be covered by a primary key or a unique constraint, and the two columns need compatible types. That is why book_authors.book_id is bigint, matching books.book_id.
The "many" end of each line is the child, and it holds the foreign key column. readings is a child of books, so readings.book_id carries the foreign key.
Declaring a foreign key
You have already seen the inline form in book_authors:
book_id bigint NOT NULL REFERENCES books (book_id) ON DELETE CASCADEPostgreSQL names this constraint book_authors_book_id_fkey. You can also add a foreign key to an existing table, which lets you choose the name. To try this, create a scratch table for notes about books:
CREATE TABLE book_notes (
note_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
book_id bigint NOT NULL,
body text NOT NULL
);
ALTER TABLE book_notes
ADD CONSTRAINT book_notes_book_id_fkey
FOREIGN KEY (book_id) REFERENCES books (book_id)
ON DELETE CASCADE;Name constraints explicitly when you add them with ALTER TABLE. Error messages, migrations and DROP CONSTRAINT all refer to that name.
To list every foreign key in the database, query the catalog:
SELECT conrelid::regclass AS child_table,
conname,
pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE contype = 'f'
ORDER BY 1, 2;What the database rejects
Insert a reading for a book that does not exist:
INSERT INTO readings (book_id) VALUES (999999);ERROR: insert or update on table "readings" violates foreign key constraint "readings_book_id_fkey"
DETAIL: Key (book_id)=(999999) is not present in table "books".The check also protects the parent side. Deleting a book that has a reading fails:
ERROR: update or delete on table "books" violates foreign key constraint "readings_book_id_fkey" on table "readings"
DETAIL: Key (book_id)=(1) is still referenced from table "readings".Both errors carry SQLSTATE 23503 (foreign_key_violation). Application code can catch that code and show a useful message.
Referential actions
The ON DELETE and ON UPDATE clauses decide what happens to child rows when a parent row is deleted or its key changes.
| Action | Effect when the parent row is deleted |
|---|---|
| `NO ACTION` (default) | Raises an error. The check runs at the end of the statement, and it can be postponed if the constraint is deferrable. |
| `RESTRICT` | Raises an error immediately. It can't be deferred. |
| `CASCADE` | Deletes the child rows too. |
| `SET NULL` | Sets the child column to NULL. The column must allow NULL. |
| `SET DEFAULT` | Sets the child column to its default value. That default must itself exist in the parent. |
For everyday purposes, NO ACTION and RESTRICT behave the same. The difference only shows up with deferred constraints and with statements that change many rows at once.
The schema uses three of these on purpose:
book_authors.book_idusesCASCADE. A link row has no meaning without its book, so it should disappear with it.book_authors.author_idusesRESTRICT. Deleting an author should never silently erase which books they wrote. You must remove or reassign the links first.readings.book_iduses the defaultNO ACTION. You can't delete a book that has reading history, which protects the log.
Check the cascade on the scratch table:
INSERT INTO books (title) VALUES ('Scratch Book');
INSERT INTO book_notes (book_id, body)
SELECT book_id, 'A note that should vanish' FROM books WHERE title = 'Scratch Book';
DELETE FROM books WHERE title = 'Scratch Book';
SELECT count(*) FROM book_notes;The count is 0, because the note went away with its book.
ON UPDATE accepts the same actions. With identity primary keys that never change, you rarely need it, so the default is fine.
In PostgreSQL 15 and newer, SET NULL and SET DEFAULT can name specific columns, as in ON DELETE SET NULL (column_name). This matters for composite foreign keys, where you may not want to null the whole key. Version 12 through 14 reject that syntax.
NULL values and optional links
A NULL in a foreign key column is never checked against the parent. That makes the link optional. If the relationship is mandatory, add NOT NULL on the column, as every foreign key in this schema does. Without it, a row with book_id NULL is valid, and it would drop out of every inner join.
For composite foreign keys, the default MATCH SIMPLE skips the check if any column is NULL. MATCH FULL instead requires that all columns are NULL or none are. Our schema has no composite foreign keys, but you may need MATCH FULL if you add one later.
Adding a foreign key to a table that already has data
ADD CONSTRAINT ... FOREIGN KEY scans the whole child table to verify existing rows. While it scans, it blocks writes. On a large table, split it into two steps:
ALTER TABLE readings
ADD CONSTRAINT readings_book_id_checked_fkey
FOREIGN KEY (book_id) REFERENCES books (book_id)
NOT VALID;
ALTER TABLE readings
VALIDATE CONSTRAINT readings_book_id_checked_fkey;NOT VALID enforces the rule for new and changed rows immediately, without checking old ones. VALIDATE CONSTRAINT then checks the old rows with a weaker lock that still lets normal reads and writes continue. This example adds a second constraint on readings.book_id purely as a demonstration. Drop it afterwards:
ALTER TABLE readings DROP CONSTRAINT readings_book_id_checked_fkey;Deferrable constraints
By default, PostgreSQL checks a foreign key at the end of each statement. Declaring it DEFERRABLE INITIALLY DEFERRED moves the check to commit time. Inside a transaction you can then insert child rows before their parents. This helps with bulk loads and with two tables that point at each other. Use it only when you need it. Most designs, including this one, don't.
Foreign keys do not create indexes
PostgreSQL indexes the parent column automatically, because a primary key or unique constraint is backed by an index. It does not index the child column. That has two costs:
- Deleting or changing a parent row forces PostgreSQL to find matching child rows. Without an index on the child column, it scans the whole child table.
- Joins from parent to child, such as "all readings for this book", scan too.
In our schema, the primary key (book_id, author_id) on book_authors already serves lookups by book_id. Lookups by author_id and by readings.book_id need their own indexes. A later chapter on indexing builds them.
Common mistakes
- Forgetting
NOT NULLon a mandatory link, so orphan rows slip in as NULLs. - Using
CASCADEeverywhere. A mistaken delete then removes more data than intended. - Mismatched types, such as
integerreferencingbigint. PostgreSQL may accept compatible types, but join performance and future key changes suffer. - Not indexing child columns, which makes parent deletes slow.
- Dropping a parent table that has dependents.
DROP TABLE booksfails while other tables reference it.DROP TABLE books CASCADEremoves the foreign key constraints, not the child tables, so the links are silently lost.
Clean up the scratch table before moving on:
DROP TABLE book_notes;Exercise
In the schema from this chapter, you run DELETE FROM authors WHERE authorid = 1, and that author has rows in bookauthors. What happens, and why? What would you change if you wanted the link rows to be removed automatically?
Show answer
The statement fails with a foreignkeyviolation (SQLSTATE 23503), because bookauthors.authorid is declared ON DELETE RESTRICT. To delete the author's links automatically, you would drop the constraint and re-add it with ON DELETE CASCADE. Whether you should is a design decision, since it would let you erase an author's credits with a single delete.
Exercise
A table has a nullable foreign key column and you insert a row with NULL in it. Is the insert accepted, and why does this matter for joins?
Show answer
Yes, the insert is accepted, because PostgreSQL does not check NULL foreign key values against the parent. An inner join on that column will not match the row, so it disappears from the results. Declare the column NOT NULL if the relationship is mandatory.