Foreign keys
fk
Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.
A foreign key references the primary key or a unique constraint of a table (itself allowed), with columns of the same types; MATCH SIMPLE (a row with a NULL in its key references nothing). Checks run at the end of each statement, so a statement may insert a parent after its child, or swap keys:
- child side — every inserted row, and every updated row whose key changed, must find its referenced row: a point lookup on the parent’s primary or unique index;
- parent side — for every deleted row, or updated row whose referenced
key changed (unless another row now holds the key), the referencing rows
are found (through an index whose leading columns are the foreign key, or
a full scan) and the action runs:
NO ACTION/RESTRICTfail (23503),CASCADEdeletes them or updates their columns,SET NULL/SET DEFAULTupdate them (a default must reference a row too). Cascaded writes run the same checks, recursively.
Both lookups are validated reads (§5.2): an insert racing the delete of its
parent fails one of the two transactions at commit with 40001, at any
isolation level, while children of one parent do not conflict with each
other. PostgreSQL blocks on row locks instead. Index the foreign key
columns: a parent-side check without such an index reads, and so
validates, the whole child table. Not supported: deferrable constraints,
MATCH FULL. DROP TABLE of a referenced table needs CASCADE (which
drops the referencing constraints); dropping an index a foreign key needs
is refused (2BP01).