← Back to PostgreSQL, page 1

postgresql-0006 · Easy fresher

Write a foreign key that deletes child rows with the parent, and show what happens without it.

A foreign key with ON DELETE CASCADE deletes child rows when the parent row is deleted. The default, NO ACTION, raises an error if children exist, and ON DELETE SET NULL clears the reference. Choose per relationship: order lines belong to their order, but orders should usually not vanish with a customer.

Full answer

Setup for the example:

sql
CREATE TABLE orders (id int PRIMARY KEY, customer text);
CREATE TABLE order_lines (
  order_id int REFERENCES orders(id) ON DELETE CASCADE,
  item text
);
CREATE TABLE invoices (
  id int PRIMARY KEY,
  order_id int REFERENCES orders(id)
);
INSERT INTO orders VALUES (1, 'Asha'), (2, 'Ben');
INSERT INTO order_lines VALUES (1, 'pen'), (1, 'ink'), (2, 'pad');
INSERT INTO invoices VALUES (10, 2);
sql
DELETE FROM orders WHERE id = 1; SELECT order_id, item FROM order_lines ORDER BY item;

PostgreSQL returns:

text
 order_id | item
----------+------
 2        | pad
(1 row)
sql
DELETE FROM orders WHERE id = 2;

Result on PostgreSQL 17:

text
ERROR:  update or delete on table "orders" violates foreign key constraint "invoices_order_id_fkey" on table "invoices"

Deleting order 1 also removed its two lines, leaving only order 2's line. Deleting order 2 fails, because an invoice still refers to it and that foreign key uses the default NO ACTION rule; the error names the constraint and the referencing table. PostgreSQL does not index foreign-key columns automatically, so add an index on order_lines(order_id): without it, each parent delete scans the child table to find matching rows.

sql
CREATE TABLE orders (id int PRIMARY KEY, customer text);
CREATE TABLE order_lines (
  order_id int REFERENCES orders(id) ON DELETE CASCADE,
  item text
);
CREATE TABLE invoices (
  id int PRIMARY KEY,
  order_id int REFERENCES orders(id)
);
INSERT INTO orders VALUES (1, 'Asha'), (2, 'Ben');
INSERT INTO order_lines VALUES (1, 'pen'), (1, 'ink'), (2, 'pad');
INSERT INTO invoices VALUES (10, 2);

DELETE FROM orders WHERE id = 1; SELECT order_id, item FROM order_lines ORDER BY item;

DELETE FROM orders WHERE id = 2;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • ON DELETE CASCADE removes children
  • Default NO ACTION blocks deletes
  • SET NULL clears references
  • Index foreign-key columns yourself
  • Choose the rule per relationship

Common mistakes

  • Cascading deletes through business records
  • Forgetting the index on the referencing column

Follow-ups

  • When would you use ON DELETE RESTRICT?
  • How do deferrable foreign keys work?

Tips

  • Mention the missing index