Skip to content
We areTOP 1%

What is a foreign key, and what do ON DELETE CASCADE and ON DELETE SET NULL do?

MediumConceptKeys & Constraints
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

A foreign key is a column in a child table whose value must match an existing primary key (or unique key) in a parent table, or be NULL. It enforces referential integrity: a row cannot point to something that does not exist.

  • Inserting a child row with a parent value that does not exist is rejected.
  • Referential actions decide what happens to child rows when the parent row is deleted or its key changes: RESTRICT or NO ACTION (the default) rejects the change, CASCADE deletes or updates the child rows too, and SET NULL sets the child column to NULL.
  • Index foreign key columns: MySQL InnoDB creates such an index automatically, but PostgreSQL does not.

Example: employees.dept_id references departments.id

departments       employees
id | name         id | name | dept_id
10 | CSE          1  | Asha | 10
20 | ECE          2  | Ravi | 20
INSERT INTO employees VALUES (3, 'Kiran', 30);  -- fails: no dept 30
DELETE FROM departments WHERE id = 20;
-- RESTRICT: fails;  CASCADE: Ravi is deleted;  SET NULL: Ravi's dept_id becomes NULL

More in Keys & Constraints

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account