Difficulty: Beginner
What is a foreign key, and what do ON DELETE actions like CASCADE, SET NULL and RESTRICT do?
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.
With orders.customer_id REFERENCES customers(id):
ON DELETE action.NULL foreign key is allowed unless the column is NOT NULL; it simply means "no reference".| Action | Effect when the parent row is deleted | Typical use |
|---|---|---|
NO ACTION (default) | Error if children exist (checked at end of statement, deferrable in Postgres) | Most relationships |
RESTRICT | Error immediately, cannot be deferred | Strict protection |
CASCADE | Child rows are deleted too | Owned data: order → order_items |
SET NULL | Child FK column set to NULL | Optional links: task → assignee |
SET DEFAULT | Child FK set to the column default | Rare; fallback category |
The same options exist for ON UPDATE, though updating primary keys is uncommon when you use surrogate keys.
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.
DEFERRABLE INITIALLY DEFERRED in Postgres) so checks happen at commit.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.
Foreign Key, Referential Integrity, ON DELETE CASCADE, ON DELETE SET NULL, RESTRICT