What is a foreign key, and what do ON DELETE CASCADE and ON DELETE SET NULL do?
MediumConceptKeys & Constraints
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:
RESTRICTorNO ACTION(the default) rejects the change,CASCADEdeletes or updates the child rows too, andSET NULLsets the child column toNULL. - 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
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | What are super, candidate, primary, alternate and composite keys? | Concept | Easy | Read the answer to What are super, candidate, primary, alternate and composite keys? | |||
| 2 | What is the difference between a primary key and a unique key? | Concept | Easy | Read the answer to What is the difference between a primary key and a unique key? | |||
| 3 | What are integrity constraints in DBMS? | Concept | Easy | Read the answer to What are integrity constraints in DBMS? | |||
| 4 | What is a foreign key, and what do ON DELETE CASCADE and ON DELETE SET NULL do? | Concept | Medium | Read the answer to What is a foreign key, and what do ON DELETE CASCADE and ON DELETE SET NULL do? |