Sub topic 10
Choosing ON DELETE and ON UPDATE behavior
This chapter assumes you can write a CREATE TABLE statement with a PRIMARY KEY and a FOREIGN KEY, and that you know basic INSERT, UPDATE, and DELETE. A foreign key blocks child rows that point to a missing parent. This chapter covers the other direction: what the database does when you delete or change a parent row that child rows still reference.
What a referential action is
A referential action is the rule a foreign key applies when the parent row it points to is deleted or has its key changed. You declare it with ON DELETE and ON UPDATE clauses at the end of the foreign key definition:
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
ON DELETE RESTRICT
ON UPDATE CASCADEThe two clauses are independent. Each takes one of five actions, and you can leave either one out.
| Action | Effect on child rows when the parent is deleted or its key changes |
|---|---|
| `NO ACTION` | The statement fails if child rows would be orphaned. The check happens at the end of the statement. This is the default. |
| `RESTRICT` | The statement fails immediately if child rows exist. |
| `CASCADE` | The change is copied to the children. A delete removes them. A key update rewrites their foreign key value. |
| `SET NULL` | The child's foreign key columns become `NULL`. |
| `SET DEFAULT` | The child's foreign key columns take their `DEFAULT` value. |
NO ACTION versus RESTRICT
Both actions reject a delete that would leave orphans, so day to day they look the same. The difference is timing. RESTRICT rejects the statement at once. NO ACTION waits until the end of the statement, so a statement that temporarily breaks the rule and repairs it before finishing can still succeed. In PostgreSQL, a foreign key declared DEFERRABLE with NO ACTION can postpone the check to the end of the transaction. RESTRICT cannot be deferred.
Dialects differ here. In MySQL with InnoDB, NO ACTION and RESTRICT behave the same way. SQL Server has no RESTRICT keyword, and NO ACTION is its default.
ON DELETE in practice
Choose the action by asking what the child row means without its parent.
RESTRICTorNO ACTIONfits records you must keep. An order is a financial record, so deleting a customer who has orders should fail. This is the safe default.CASCADEfits rows that only exist as part of the parent. Order items have no meaning without their order, so deleting the order removes them.SET NULLfits an optional link. A support ticket can outlive the agent who handled it.SET DEFAULTfits links that should fall back to a placeholder row, such as an "unassigned" agent. It is rare. The default value must itself match an existing parent row, or the action fails.
This script, written for PostgreSQL, shows SET NULL and CASCADE together:
CREATE TABLE agents (
agent_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE tickets (
ticket_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
agent_id INTEGER,
subject VARCHAR(200) NOT NULL,
CONSTRAINT fk_tickets_agent
FOREIGN KEY (agent_id) REFERENCES agents (agent_id)
ON DELETE SET NULL
);
CREATE TABLE ticket_notes (
note_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
ticket_id INTEGER NOT NULL,
body TEXT NOT NULL,
CONSTRAINT fk_notes_ticket
FOREIGN KEY (ticket_id) REFERENCES tickets (ticket_id)
ON DELETE CASCADE
);
INSERT INTO agents (name) VALUES ('Grace');
INSERT INTO tickets (agent_id, subject) VALUES (1, 'Login fails');
INSERT INTO ticket_notes (ticket_id, body) VALUES (1, 'Reproduced the error.');
DELETE FROM agents WHERE agent_id = 1;
SELECT ticket_id, agent_id FROM tickets;
-- ticket 1 still exists and its agent_id is now NULL
DELETE FROM tickets WHERE ticket_id = 1;
SELECT COUNT(*) FROM ticket_notes;
-- 0: the note was removed by the cascadeDeleting the agent leaves the ticket in place with agent_id set to NULL. Deleting the ticket then removes its notes.
Reading a rejected delete
With RESTRICT or NO ACTION, deleting a referenced customer fails and changes nothing. PostgreSQL reports it like this:
ERROR: update or delete on table "customers" violates foreign key constraint "fk_orders_customer" on table "orders"
DETAIL: Key (customer_id)=(1) is still referenced from table "orders".The message names the constraint and the child table. This is one reason to name constraints, as the naming chapter explains.
ON UPDATE
ON UPDATE runs when the referenced key value itself changes. With an identity column as the parent key, this almost never happens, and PostgreSQL rejects updates to a GENERATED ALWAYS identity column anyway. You therefore rarely need ON UPDATE with surrogate keys, and leaving it as the default is fine.
It matters for natural keys, which are real-world values that can be corrected:
CREATE TABLE currencies (
code CHAR(3) PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE prices (
product_id INTEGER NOT NULL,
currency_code CHAR(3) NOT NULL,
amount NUMERIC(10, 2) NOT NULL,
PRIMARY KEY (product_id, currency_code),
FOREIGN KEY (currency_code) REFERENCES currencies (code)
ON UPDATE CASCADE
ON DELETE RESTRICT
);If someone entered a wrong code, UPDATE currencies SET code = 'EUR' WHERE code = 'EUA' rewrites every matching row in prices. Without ON UPDATE CASCADE, that update would fail while prices still use the old code.
Edge cases and failure modes
- Cascades chain. If
orderscascades toorder_items, andcustomerscascades toorders, deleting one customer silently removes their orders and all items. Trace the whole chain before you chooseCASCADEnear the top of a schema. SET NULLneeds a nullable column. If the foreign key column isNOT NULL, some systems reject the constraint when you create it. Others accept it and fail when a delete triggers the action.SET DEFAULTneeds a valid default. The default must point to an existing parent row. Otherwise the action fails with a foreign key violation.- Multiple cascade paths. SQL Server refuses to create a table when cascades could reach the same table by more than one route, with a "may cause cycles or multiple cascade paths" error. Use
NO ACTIONon one path and handle that delete in application code or a procedure. - Cascades can be slow. The database must find child rows for each deleted parent. Without an index on the child's foreign key column, that is a scan of the child table. PostgreSQL does not create this index for you. The chapter on constraints and indexes covers it.
- Cascades bypass your application. Logging, soft-delete flags, and file cleanup tied to a child row will not run when the database deletes it for you. MySQL InnoDB also does not fire triggers for cascaded changes.
A quick decision guide
| Relationship | Typical choice |
|---|---|
| Order belongs to customer | `ON DELETE RESTRICT` |
| Order item belongs to order | `ON DELETE CASCADE` |
| Ticket optionally assigned to agent | `ON DELETE SET NULL` |
| Row with a natural key that may be corrected | `ON UPDATE CASCADE` |
| Surrogate identity key | Leave `ON UPDATE` unset |
Exercise
A table comments has a nullable column reviewer_id that references staff (staff_id). You want comments to survive when a staff member is deleted, with no reviewer recorded. Which clause do you add to the foreign key? What happens to the comments after DELETE FROM staff WHERE staff_id = 7?
Show answer
Add ON DELETE SET NULL. The delete of staff member 7 succeeds, and every comment that had reviewer_id = 7 keeps its row but now has reviewer_id set to NULL. This only works because the column is nullable.
Exercise
In your schema, customers cascades to orders, and orders cascades to order_items. What does DELETE FROM customers WHERE customer_id = 1 do, and which action would you change to make the delete fail instead?
Show answer
It deletes the customer, all of that customer's orders, and all items of those orders. To make the delete fail while orders exist, change the foreign key from orders to customers to ON DELETE RESTRICT (or NO ACTION).