Memra

Foreign-key actions

◈ 2 cards

Decide what happens to children when a parent is deleted.

ON DELETE / ON UPDATE

A foreign key can specify what happens to dependent rows when the referenced row is deleted (or its key updated):

  • ON DELETE RESTRICT (default) — refuse the delete if children exist
  • ON DELETE CASCADE — delete the children too
  • ON DELETE SET NULL — keep the children but null out the reference
CREATE TABLE child (
  id int PRIMARY KEY,
  parent_id int REFERENCES parent(id) ON DELETE CASCADE
);

This is how you encode real-world rules — delete an order and its line items should go with it (CASCADE); delete a category and products should just lose their category (SET NULL).

RESTRICTCASCADESET NULLDELETE parent 1errorchild 10 still referschild 10 goneorder → itemsparent_id NULLchild 10 survives
Same statement, three schemas, three different worlds. The choice is made once in the CREATE TABLE and it encodes a real-world rule: line items cannot outlive their order (CASCADE), but an employee can outlive their department (SET NULL).
NORMAL ~/memra/learn/postgresql/foreign-key-actions utf-8 LF