Video in progress

Why do we need a FOREIGN KEY, and what does ON DELETE CASCADE do?

A FOREIGN KEY guarantees, at the database level, that a value in one table really exists in another. ON DELETE CASCADE automatically deletes the dependent rows when the parent row is deleted.

📖 Answer

Without an FK, a bug in your code can write orders.user_id = 999 when no user 999 exists. Those "orphan" rows later break your reports. With an FK, the database rejects such an INSERT itself.

CREATE TABLE order_items (
    id       bigint PRIMARY KEY,
    order_id bigint NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
    product  text   NOT NULL
);

The ON DELETE options:

  • NO ACTION / RESTRICT (close to the default): you can't delete a parent row that has children;
  • CASCADE: the children are deleted too;
  • SET NULL: the column in the children becomes NULL.

Use CASCADE with care. It makes sense for an order and its line items. But if deleting a users row also wipes the payment history, that is usually not what you want.

One more gotcha: PostgreSQL does not create an index on the FK column automatically. If you don't index order_items.order_id, deleting a parent row on a big table will be slow.