foreign keys
references between tables. CASCADE, SET NULL, DEFERRABLE, and the index postgres doesn't create for you.
- address
- everything.design.foreign_keys
- part
- part 7, schema design
- chapter
- chapter 4 of 13
- reading time
- 9 min
a foreign key says every value in these columns must exist as a key in that table. postgres checks it on both sides: inserting a child, and deleting or re-keying a parent. the referential action (NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT) decides what a parent delete does to its children.
two costs people miss: postgres doesn't index the referencing column for you, so every parent delete scans the child table; and every child insert takes a FOR KEY SHARE lock on its parent row.
the picture
you know the orphan rows every app eventually finds? an order whose customer was deleted in 2023, a comment on a post that no longer exists. a foreign key makes them impossible: the database refuses any write that would create one.
think of a library card catalogue where every loan slip names a book by its number (the child points at the parent's key). the librarian won't file a slip for a book that isn't on the shelf, and won't throw a book away while slips still name it, unless you've said in advance what should happen to the slips.
- 1DELETE FROM authors WHERE id = 1;
- 2SELECT id, author_id, title FROM posts ORDER BY id;
the default. the delete would orphan two posts, so it fails: 23503.
declaring one
CREATE TABLE customers (id int PRIMARY KEY, name text NOT NULL);
CREATE TABLE orders (
id int PRIMARY KEY,
customer_id int NOT NULL REFERENCES customers (id),
total numeric(8,2) NOT NULL
);
INSERT INTO customers VALUES (42, 'Ada Lovelace');
INSERT INTO orders VALUES (1, 42, 22.00);the referenced columns must have a primary key or a UNIQUE constraint (postgres needs an index to look parents up fast, and a guarantee there's only one). both sides are checked:
INSERT INTO orders VALUES (2, 99, 5.00);
DELETE FROM customers WHERE id = 42;note the NOT NULL on customer_id. a foreign key column can be NULL unless you say otherwise, and a NULL reference is never checked: it just means "no customer". for an order that's wrong; for an optional field like manager_id it's exactly right. (with a composite foreign key and the default MATCH SIMPLE, one NULL column switches the check off for the whole row. MATCH FULL refuses half-NULL keys.)
the actions, and the deferred difference
| action | on parent delete (or key update) | use it for |
|---|---|---|
| NO ACTION (default) | error, unless the children are gone by the time the check runs | almost everything |
| RESTRICT | error, immediately, even if the constraint is deferred | "never, not even mid-transaction" |
| CASCADE | delete (or re-key) the children too | children that make no sense alone: order lines of an order |
| SET NULL | set the reference to NULL | optional links: a post whose author left |
| SET DEFAULT | set it to the column default, which must exist as a parent | a "deleted user" placeholder row |
NO ACTION and RESTRICT look identical in the figure. the difference is when. NO ACTION is checked at the end of the statement, or at COMMIT if the constraint is deferred, so a transaction may delete a parent and put it back. RESTRICT checks at once, no matter what:
CREATE TABLE parents (id int PRIMARY KEY);
CREATE TABLE kids_no_action (parent_id int REFERENCES parents DEFERRABLE INITIALLY DEFERRED);
CREATE TABLE kids_restrict (parent_id int REFERENCES parents ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED);
INSERT INTO parents VALUES (1), (2);
INSERT INTO kids_no_action VALUES (1);
INSERT INTO kids_restrict VALUES (2);
BEGIN;
DELETE FROM parents WHERE id = 1; -- NO ACTION, deferred: allowed for now
INSERT INTO parents VALUES (1); -- and fixed before COMMIT
COMMIT;BEGIN;
DELETE FROM parents WHERE id = 2; -- RESTRICT ignores the deferraltransaction aborted: ROLLBACK to continue
that deferral is also how you insert rows that point at each other. two employees who are each other's buddy can't be inserted one at a time under an immediate check, but can in one transaction with a deferred one:
CREATE TABLE people (id int PRIMARY KEY, buddy_id int NOT NULL REFERENCES people DEFERRABLE INITIALLY DEFERRED);
BEGIN;
INSERT INTO people VALUES (1, 2);
INSERT INTO people VALUES (2, 1);
COMMIT;
SELECT id, buddy_id FROM people ORDER BY id;| idint4 | buddy_idint4 |
|---|---|
| 1 | 2 |
| 2 | 1 |
the column list on SET NULL and SET DEFAULT pg 15+ matters for multi-tenant keys like (tenant_id, author_id): plain SET NULL would blank tenant_id too, and it's NOT NULL, so the delete would fail. ON DELETE SET NULL (author_id) blanks just the one column, which is the last option in the figure.
the index postgres doesn't make
a foreign key needs an index on the referenced side, and you already have it (the primary key). the referencing side, orders.customer_id, gets nothing. the shop dataset is built exactly like that, on purpose.
(order_items.order_id is covered: it leads the table's primary key, (order_id, line_no). product_id and customer_id are not.)
so what does deleting a customer cost? take ten customers who never ordered (Ming Li, id 7, is the first). deleting them should be trivial:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
DELETE FROM customers WHERE id IN (7, 475, 518, 549, 557, 622, 629, 730, 756, 772);the delete itself is one index scan of customers. but look at the last line: the foreign key's trigger ran 10 times, once per deleted row, and EXPLAIN shows nothing of what it did. each call runs a query like this one (the shape postgres's RI code uses), and here's its plan:
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT 1 FROM ONLY orders AS x WHERE customer_id = 772 FOR KEY SHARE OF x;a seq scan of all 10,000 orders to find zero rows, for every customer deleted. deleting a thousand customers reads ten million order rows. add the index and the same check is one index search:
CREATE INDEX orders_customer_id_idx ON orders (customer_id);
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT 1 FROM ONLY orders AS x WHERE customer_id = 772 FOR KEY SHARE OF x;so: index every foreign key column whose parent rows get deleted or re-keyed, and every one you join on (which is most of them). the exception is a big child table whose parents are never deleted, where the index is pure write cost (what indexes cost). to find the unindexed ones, compare pg_constraint (contype f, conkey) with pg_index (indkey) and look for foreign keys whose columns aren't a leading prefix of any index.
the lock on the parent
inserting an order has to make sure customer 42 still exists at commit, and keeps existing. postgres does that by locking the parent row in the weakest row lock mode, FOR KEY SHARE: it blocks only a delete, or an update that changes the key.
- T1RowShareLockcustomers
- T1RowShareLockcustomers_pkey
- T1RowExclusiveLockorders
- T1ExclusiveLockxid 761
- T1ExclusiveLock4/4
T1 places an order for customer 42 and doesn't commit yet. the foreign key check locks Ada's row FOR KEY SHARE, so nobody can delete her, or change her id, before T1 is done.
that's why T2's UPDATE didn't wait: an update that leaves key columns alone takes FOR NO KEY UPDATE, which doesn't conflict with KEY SHARE (postgres 9.3 split the modes for exactly this). on a popular parent row (one tenant, one product everyone orders) many concurrent inserts each take KEY SHARE on the same row, and postgres has to record all those lockers in a MultiXact. the full row-lock conflict table is in row-locking clauses, and how the locks are stored is in row lock internals.
-- T1, still open:
BEGIN;
INSERT INTO orders VALUES (5, 42, 9.00);
-- T2, meanwhile:
UPDATE customers SET name = 'Ada King' WHERE id = 42;keylines
- a foreign key is checked on child writes and on parent deletes and key updates.
- NO ACTION checks at the end (or at COMMIT if deferred); RESTRICT checks at once.
- SET NULL (col) and SET DEFAULT (col), 15+, touch only the listed columns.
- postgres doesn't index the referencing column: every parent delete scans the child without one.
- child inserts take FOR KEY SHARE on the parent: deletes wait, ordinary updates don't.