skip to content

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.

on delete =
authors.sql
  1. 1DELETE FROM authors WHERE id = 1;
  2. 2SELECT id, author_id, title FROM posts ORDER BY id;
ERROR: update or delete on table "authors" violates foreign key constraint "posts_author_id_fkey" on table "posts"SQLSTATE 23503

the default. the delete would orphan two posts, so it fails: 23503.

real output, postgres 18.6 (PGlite 0.5.12) · fk-actions
delete author 1 (Ada) under each action, and look at her posts. NO ACTION and RESTRICT refuse; CASCADE deletes the posts; SET NULL and SET DEFAULT keep them and change the reference. the last one is postgres 15's column list, for a key with two columns.

declaring one

schema.sqlempty db · session fk
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);
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE TABLE
#3 · INSERT 0 1
#4 · INSERT 0 1

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:

sqlempty db · session fk
continues session fk (1 earlier block run first)
INSERT INTO orders VALUES (2, 99, 5.00);
DELETE FROM customers WHERE id = 42;
output, from postgres 18.6
#1 · ERROR 23503
ERROR 23503: insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL: Key (customer_id)=(99) is not present in table "customers".
#2 · ERROR 23503
ERROR 23503: update or delete on table "customers" violates foreign key constraint "orders_customer_id_fkey" on table "orders"
DETAIL: Key (id)=(42) is still referenced from table "orders".

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

actionon parent delete (or key update)use it for
NO ACTION (default)error, unless the children are gone by the time the check runsalmost everything
RESTRICTerror, immediately, even if the constraint is deferred"never, not even mid-transaction"
CASCADEdelete (or re-key) the children toochildren that make no sense alone: order lines of an order
SET NULLset the reference to NULLoptional links: a post whose author left
SET DEFAULTset it to the column default, which must exist as a parenta "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:

sqlempty db · session defer
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;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · CREATE TABLE
#3 · CREATE TABLE
#4 · INSERT 0 2
#5 · INSERT 0 1
#6 · INSERT 0 1
#7 · BEGIN
#8 · DELETE 1
#9 · INSERT 0 1
#10 · COMMIT
sqlempty db · session defer
continues session defer (1 earlier block run first)
BEGIN;
DELETE FROM parents WHERE id = 2;   -- RESTRICT ignores the deferral
output, from postgres 18.6
#1 · BEGIN
#2 · ERROR 23001
ERROR 23001: update or delete on table "parents" violates RESTRICT setting of foreign key constraint "kids_restrict_parent_id_fkey" on table "kids_restrict"
DETAIL: Key (id)=(2) is referenced from table "kids_restrict".

transaction 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:

sqlempty db
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;
output, from postgres 18.6
#1 · CREATE TABLE
#2 · BEGIN
#3 · INSERT 0 1
#4 · INSERT 0 1
#5 · COMMIT
#6 · SELECT 2
idint4buddy_idint4
12
21
(2 rows)

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.

customersidpknameemailuniqueordersidpkcustomer_idfkstatusorder_itemsorder_idpk fkproduct_idfkqtyproductsidpkskuuniqueprice
foreign key → primary keyreferencing column, no index
drawn by hand · from datasets/shop/schema.sql
the shop's foreign keys. each line ends at a primary key, which has an index. the columns in dead are the referencing sides, and none of them has one.

(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:

sqldb=shop · session noidx
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);
output, from postgres 18.6
EXPLAIN
Delete on customers (actual rows=0.00 loops=1) -> Index Scan using customers_pkey on customers (actual rows=10.00 loops=1) Index Cond: (id = ANY ('{7,475,518,549,557,622,629,730,756,772}'::integer[])) Index Searches: 3 Trigger for constraint orders_customer_id_fkey: calls=10

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:

sqldb=shop · session noidx
continues session noidx (1 earlier block run first)
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;
output, from postgres 18.6
EXPLAIN
LockRows (actual rows=0.00 loops=1) -> Seq Scan on orders x (actual rows=0.00 loops=1) Filter: (customer_id = 772) Rows Removed by Filter: 10000

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:

sqldb=shop · session noidx
continues session noidx (2 earlier blocks run first)
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;
output, from postgres 18.6
#1 · CREATE INDEX
#2 · EXPLAIN
LockRows (actual rows=0.00 loops=1) -> Bitmap Heap Scan on orders x (actual rows=0.00 loops=1) Recheck Cond: (customer_id = 772) -> Bitmap Index Scan on orders_customer_id_idx (actual rows=0.00 loops=1) Index Cond: (customer_id = 772) Index Searches: 1

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.

T1
·
T2
·
1
BEGIN; INSERT INTO orders VALUES (1, 42, 22.00)→ INSERT 0 1
lock manager
  • 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.

step 1/5
real output, a postgres 18.6 server · fk-lock
two real sessions on a postgres 18.6 server. T1 inserts an order and holds its transaction open. T2 can still update Ada's city, but its DELETE waits for T1 (dashed), and when T1 commits, the delete fails: Ada has an order now. the panel is pg_locks after each step.

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.

predict the output
sql
-- 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.