Referential Integrity

Difficulty: Beginner

Question

What is a foreign key, and what do ON DELETE actions like CASCADE, SET NULL and RESTRICT do?

Answer

A foreign key is a column (or set of columns) in a child table that must match a primary key or unique key in a parent table, which guarantees that every reference points to a row that actually exists. This rule is called referential integrity. The ON DELETE and ON UPDATE actions tell the database what to do with child rows when the referenced parent row is deleted or its key changes: block it, delete the children too, or clear the reference.

What the database enforces

With orders.customer_id REFERENCES customers(id):

  • Inserting an order for customer 999 fails if customer 999 does not exist.
  • Deleting a customer who has orders triggers the configured ON DELETE action.
  • A NULL foreign key is allowed unless the column is NOT NULL; it simply means "no reference".

The referential actions

ActionEffect when the parent row is deletedTypical use
NO ACTION (default)Error if children exist (checked at end of statement, deferrable in Postgres)Most relationships
RESTRICTError immediately, cannot be deferredStrict protection
CASCADEChild rows are deleted tooOwned data: order → order_items
SET NULLChild FK column set to NULLOptional links: task → assignee
SET DEFAULTChild FK set to the column defaultRare; fallback category

The same options exist for ON UPDATE, though updating primary keys is uncommon when you use surrogate keys.

When CASCADE is right and when it is dangerous

Use CASCADE for composition: an order_item has no meaning without its order, so deleting the order should delete its items. Avoid it for association: deleting a customer should not silently wipe years of orders and invoices that finance and GST compliance need. Cascades can also chain several levels deep, turning one DELETE into millions of row deletions that hold locks for a long time.

Practical gotchas

  • Index the foreign key column. Postgres and SQL Server do not create one automatically (MySQL InnoDB does). Without it, every parent delete scans the child table, and joins are slow.
  • Ordering in bulk loads: insert parents before children, or use deferrable constraints (DEFERRABLE INITIALLY DEFERRED in Postgres) so checks happen at commit.
  • Sharded or microservice systems often cannot use database foreign keys across boundaries. Integrity then moves to application logic, events and reconciliation jobs.
  • Some teams skip FKs for write speed. That trades a small insert cost for orphaned rows and harder debugging; most teams keep them.
What happens on DELETE FROM orders WHERE id = 10. The database checks every foreign key that points at the deleted row.
  1. Find child rows referencing order 10: Uses the index on order_items.order_id if present.
  2. order_items has ON DELETE CASCADE: Its matching rows are deleted too.
  3. refunds has ON DELETE RESTRICT: If any refund exists, the whole delete fails.
  4. Commit or roll back atomically: Parent and cascaded children go together.

Code examples

Foreign keys with different delete actions

CREATE TABLE customers (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

CREATE TABLE orders (
  id          BIGINT PRIMARY KEY,
  customer_id BIGINT NOT NULL
    REFERENCES customers(id) ON DELETE RESTRICT  -- keep order history
);
CREATE INDEX ON orders (customer_id);           -- not automatic in Postgres

CREATE TABLE order_items (
  order_id BIGINT REFERENCES orders(id) ON DELETE CASCADE,  -- owned data
  sku      TEXT,
  qty      INT,
  PRIMARY KEY (order_id, sku)
);

CREATE TABLE support_tickets (
  id       BIGINT PRIMARY KEY,
  agent_id BIGINT REFERENCES agents(id) ON DELETE SET NULL  -- optional link
);

DELETE FROM customers WHERE id = 1;
-- ERROR: update or delete on table "customers" violates foreign key
-- constraint "orders_customer_id_fkey" on table "orders"

Each relationship gets the action that matches its meaning: history is protected, owned rows are cleaned up, and optional links are cleared.

Key points

  • Foreign keys guarantee every reference points to an existing parent row.
  • Default NO ACTION and RESTRICT both block deletes of referenced parents.
  • CASCADE suits owned child data; avoid it for business records you must retain.
  • Index foreign key columns; Postgres does not do it automatically.
  • Cross-service or cross-shard references cannot use database FKs.

Common follow-up questions

  • What is the difference between NO ACTION and RESTRICT?
  • Why should foreign key columns be indexed?
  • How do you maintain referential integrity across microservices?
  • What are deferrable constraints and when are they useful?

Interview tips

  • Explain CASCADE with a composition vs association example; it shows design judgement.
  • Mention the missing-index-on-FK performance trap.
  • Do not claim foreign keys are "bad for performance" without nuance.

Concepts covered

Foreign Key, Referential Integrity, ON DELETE CASCADE, ON DELETE SET NULL, RESTRICT

More Database Design questions