Foreign Keys & Referential Integrity (ON DELETE CASCADE, SET NULL)
Enforce parent-child links and choose delete/update actions that keep data consistent.
In plain words
A foreign key makes sure a row only points to things that really exist, and says what to do with the pointing rows if the thing is deleted.
Think of it like…
A library: every loan slip must name a member who actually exists. If a member leaves, the library either refuses until their loans are returned (RESTRICT), throws their slips away (CASCADE), or keeps the slips but blanks the member name (SET NULL).
Where you’ve seen it
ALTER TABLE orders ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE RESTRICT;: now an order can't reference a missing customer, and a customer with orders can't be deleted by accident.
Words you’ll hear
- Parent / child
- The referenced table (customers) and the referencing table (orders).
- Orphan row
- A child row whose parent doesn't exist; foreign keys prevent it.
- Referential action
- CASCADE, RESTRICT, NO ACTION, SET NULL or SET DEFAULT on delete or update.
- Deferrable
- A constraint checked at COMMIT instead of after each statement.
Visual diagram
Theory & example queries
What the database enforces
On every insert or update of the child, the database checks that the referenced parent exists, and rejects the change if not. On every delete or key update of the parent, it checks for children and applies the referential action. NULL in the child column is allowed unless the column is NOT NULL, which is how optional relationships work.
The actions: NO ACTION (the default) and RESTRICT both refuse to delete a parent that still has children; NO ACTION can be deferred to the end of the transaction, RESTRICT can't. CASCADE deletes or updates the children too. SET NULL and SET DEFAULT keep the children but change their reference.
| id | order_id | product_id | qty | price |
|---|---|---|---|---|
| 1 | 101 | 42 | 2 | 49.5 |
| 2 | 101 | 84 | 1 | 150 |
| 3 | 102 | 42 | 1 | 49.5 |
CREATE TABLE order_items ( id bigint PRIMARY KEY, order_id bigint NOT NULL REFERENCES orders(id) ON DELETE CASCADE, …);PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Expected output
Note: Representative status for the completed DDL; the ellipsis stands for the remaining product and quantity columns.
Items have no meaning without their order, so deleting the order deletes them.
Key takeaway: CASCADE for parts of a whole, RESTRICT for independent records, SET NULL for optional links.
Performance and migrations
When a parent is deleted, the database must find its children. Without an index on the child column, that's a full scan of the child table for every deleted parent. PostgreSQL doesn't create that index automatically (MySQL InnoDB does), so add it yourself.
Adding a foreign key to a big existing table checks every row while holding a lock. In PostgreSQL, add it with NOT VALID (new rows are checked immediately) and then run VALIDATE CONSTRAINT separately, which checks old rows without blocking writes.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
ALTER TABLE ordersADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
Expected output
Note: The second command fails if orphan customer_id values remain; otherwise validation succeeds after existing rows are checked.
then
Key takeaway: Index the child column, and add foreign keys to big tables in two steps.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Identify the relationship
Find which column refers to which parent key, and whether the relationship is required (NOT NULL) or optional.
orders.customer_id → customers.id
When to use it & trade-offs
What it is
A foreign key declares that values in a child column must exist in a parent table's primary key (or unique) column, such as orders.customer_id referencing customers.id. The database then rejects orphan rows, and the ON DELETE / ON UPDATE action decides what happens to children when a parent is deleted or its key changes.
Why it matters: Without foreign keys, bugs and manual deletes leave orders pointing at customers that no longer exist, and reports quietly lose or mislabel data. Choosing the delete action is a real design decision: cascade, block, or detach. A missing index on the child column is a classic cause of slow deletes.
When to reach for it
- Every parent-child relationship in a transactional database
- CASCADE for components of a whole
- SET NULL for optional assignments
When to avoid or be careful
- Skipping foreign keys "for performance" and accumulating orphan rows
- CASCADE on relationships where losing children would be a disaster
- Forgetting the index on the child column in PostgreSQL
Choosing an ON DELETE action
Strengths: Nothing is deleted by surprise.
Watch out: You must remove or reassign children first.
Strengths: One delete cleans up everything that belongs to the parent.
Watch out: A single delete can remove huge amounts of data, including through chains of cascades.
Strengths: Keeps the child rows and history.
Watch out: The column must be nullable, and code must handle the missing reference.
Interview signals & numbers to know
When this topic comes up
- “How do you keep data consistent between tables?”
- “What does ON DELETE CASCADE do?”
- Orphan rows
- Slow deletes on a parent table
- "violates foreign key constraint" error
Benchmarks & rules of thumb
- 5
- referential actions: NO ACTION, RESTRICT, CASCADE, SET NULL, SET DEFAULT
- NO ACTION
- the default
- 0
- automatic indexes on FK columns in PostgreSQL
Common mistakes & follow-ups
Common interview mistakes
- Using ON DELETE CASCADE from customers to orders and wiping out a customer's order history.
- Leaving the foreign key column unindexed, making every parent delete scan the whole child table.
- Adding a foreign key to a large table in one step and locking it for minutes.
Likely interviewer follow-ups
- What is the difference between RESTRICT and NO ACTION?
- Why can deleting one row from a parent table be slow?
- Would you use foreign keys in a sharded or microservice database? What are the alternatives?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Foreign Keys & Referential Integrity (ON DELETE CASCADE, SET NULL) with hands-on SQL practice and interview Q&A.