Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: Performance & internals
Stage 5: Specialization

Part 10 / Topic 4 of 9

Foreign-key actions

What should happen to loans when their book is deleted? ON DELETE makes the policy explicit:

Action Deleting the referenced row…
NO ACTION (default) / RESTRICT fails while references exist
CASCADE also deletes the referencing rows
SET NULL keeps them, clearing the reference
SET DEFAULT keeps them, resetting the reference

You met the default in shopdb — try deleting a product that order lines reference:

DELETE FROM products WHERE product_id = 1;
ERROR:  update or delete on table "products" violates foreign key constraint "order_items_product_id_fkey" on table "order_items"
DETAIL:  Key (product_id)=(1) is still referenced from table "order_items".

Protected. shopdb chose differently for order lines themselves: order_items.order_id is ON DELETE CASCADE — lines are part of their order, meaningless without it:

BEGIN;
DELETE FROM orders WHERE order_id = 7;
SELECT count(*) AS lines_for_order_7 FROM order_items WHERE order_id = 7;
ROLLBACK;
BEGIN
DELETE 1
 lines_for_order_7 
-------------------
                 0
(1 row)

ROLLBACK

The line vanished with its order (and ROLLBACK put everything back — that BEGIN/ROLLBACK safety net gets its full lesson in Part 11). Choosing: CASCADE for owned parts (lines of an order, comments of a post); RESTRICT/NO ACTION for references to independent things (products, customers) where silent deletion would be data loss; SET NULL when the relationship is optional and survivable (a product's supplier going away). The wrong CASCADE is a mass delete you didn't intend — when in doubt, restrict.

🧪 Quick quiz — answer from memory, then check.

  1. ON DELETE CASCADE on order_items.order_id means…?
  2. When is SET NULL the right action?
Show the answers
  1. Deleting an order deletes its lines too — they're owned parts, meaningless alone.
  2. When the reference is optional and rows should outlive it — like products whose supplier is dropped.

Done here? The practice set for Part 10 — 6 exercises with solutions — is on the part page.

Search the guide