Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 9/ 160
01. SQL Foundations & Relational Concepts

Foreign Keys & Referential Integrity (ON DELETE CASCADE, SET NULL)

Enforce parent-child links and choose delete/update actions that keep data consistent.

IntermediateFK · CASCADE · Integrity3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Cascading where it makes senseQuery example
1Input dataStart from the source rows or state that the statement sees.
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sqlReadable preview
1CREATE TABLE order_items (2  id bigint PRIMARY KEY,3  order_id bigint NOT NULL REFERENCES orders(id) ON DELETE CASCADE,4  …);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/4
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
CREATE TABLE

Note: Representative status for the completed DDL; the ellipsis stands for the remaining product and quantity columns.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Adding a foreign key safely in PostgreSQLQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1ALTER TABLE orders2ADD CONSTRAINT orders_customer_fk FOREIGN KEY (customer_id) REFERENCES customers (id) NOT VALID;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/2
query.sql
1ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/1
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
ALTER TABLE ALTER TABLE

Note: The second command fails if orphan customer_id values remain; otherwise validation succeeds after existing rows are checked.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

then

Key takeaway: Index the child column, and add foreign keys to big tables in two steps.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Identify the relationship

Find which column refers to which parent key, and whether the relationship is required (NOT NULL) or optional.

Focus at this step

orders.customer_id → customers.id

What to watch at this step
Required?
NOT NULL or nullable
Tip: use ← → to move between steps

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

RESTRICT / NO ACTION
Best for: Independent records like customers with orders

Strengths: Nothing is deleted by surprise.

Watch out: You must remove or reassign children first.

CASCADE
Best for: Child rows that are part of the parent (order items, post comments)

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.

SET NULL
Best for: Optional links (a ticket's assigned agent leaves the company)

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?
Interview tip: Pick a delete action for a concrete example and justify it ("order items cascade, orders restrict"). That shows you treat it as a business decision, not a syntax detail.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Primary Keys & Auto-Increment / Serial / Identity Columns
Next topic
Data Constraints (NOT NULL, UNIQUE, CHECK, DEFAULT)