Stop 10 · Schema Design & ConstraintsTopics · 6/11

Foreign Keys and ON DELETE Rules

Part of the SQL Roadmap

In short

An order pointing to a customer who no longer exists is a broken record that silently ruins reports. Foreign keys stop that from happening, and ON DELETE rules decide what to do when a parent row goes away.

A foreign key makes sure a child row always points to a real parent row. ON DELETE rules decide what happens when the parent is deleted: block it (RESTRICT or NO ACTION), delete children too (CASCADE) or clear the link (SET NULL).

The jaadu stands at the gate of a housing society holding a ring of keys, each key tied by string to a door in the apartment block behind it.

Think of it like this

Flats in a housing society

In a Gurugram housing society, every resident is registered to a real flat. If the society wants to remove a flat from its records, it has three choices: refuse while someone still lives there (RESTRICT), remove the residents' records too (CASCADE), or keep the residents but mark them 'flat not assigned' (SET NULL).

Watch it happen

Deleting customer Kavya: what happens to her rows?

customer: Kavya
order 101
order 102
item: kurta
item: dupatta
item: sandals

1/4Kavya has two orders, and the orders have items. Someone tries to delete Kavya.

The big ideas

What you need to know

Child points to parent

The foreign key column lives on the child, like orders.customer_id, and must match a real customers row or be NULL.

RESTRICT and NO ACTION

The default. You can't delete a parent while children point to it. Safest for things like customers.

CASCADE

Deleting the parent deletes its children too. Good for parts that make no sense alone, like order items.

Index the FK column

PostgreSQL doesn't index foreign key columns automatically. Add an index or parent deletes and joins get slow.

See it in code

Walk through the code

sql
1CREATE TABLE orders (2  order_id    INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,3  customer_id INTEGER NOT NULL4    REFERENCES customers (customer_id) ON DELETE RESTRICT,5  coupon_id   INTEGER6    REFERENCES coupons (coupon_id) ON DELETE SET NULL,7  amount      NUMERIC(10,2) NOT NULL8);9 10CREATE TABLE order_items (11  order_id   INTEGER NOT NULL12    REFERENCES orders (order_id) ON DELETE CASCADE,13  product_id INTEGER NOT NULL,14  quantity   INTEGER NOT NULL CHECK (quantity > 0),15  PRIMARY KEY (order_id, product_id)16);17 18CREATE INDEX ON orders (customer_id);

1/4Every order must belong to a real customer, and customers with orders can't be deleted.

Three ON DELETE rules on one schema, assuming customers and coupons already exist. MySQL (InnoDB) supports the same syntax. SQL Server has no RESTRICT keyword and uses NO ACTION, which behaves the same way.

Save yourself the pain

Common mistakes

Oops

Putting ON DELETE CASCADE on everything to avoid errors.

Do this instead

One deleted customer could wipe years of orders. Use CASCADE only for true parts of a parent, and RESTRICT for important history.

Oops

Using SET NULL on a column that is also NOT NULL.

Do this instead

The delete will fail because the database can't set it to NULL. Make the column nullable or choose another rule.

Your mission

Test each rule

~25 min

Quick check

You want order items deleted automatically when their order is deleted. Which rule fits?

Go deeper

  1. 1Add a foreign key from orders to customers and try deleting a customer who has orders.
  2. 2Recreate it with ON DELETE CASCADE and see what gets deleted.
  3. 3Decide which rule fits each relationship in a small schema and explain why.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge