Sub topic 9
Choosing ON DELETE and ON UPDATE behavior
This chapter assumes you can write CREATE TABLE, INSERT, UPDATE, and DELETE, and that you know what a primary key and a foreign key are. The examples use PostgreSQL syntax.
What referential actions are
A foreign key protects the link between a child row and its parent row. By default, the database enforces that link by refusing any change that would break it. A referential action lets you choose a different response. You attach it to the foreign key with ON DELETE and ON UPDATE.
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
ON DELETE <action>
ON UPDATE <action>ON DELETEruns when someone deletes a parent row that child rows still reference.ON UPDATEruns when someone changes the parent's referenced key value (usually the primary key).
You can set the two clauses independently. If you leave one out, the default is NO ACTION.
The five actions
| Action | What happens to the child rows | Typical use |
|---|---|---|
| `NO ACTION` | The change is rejected. The check can be postponed to the end of the statement, or of the transaction if the constraint is deferrable. | Default. Safe for most data. |
| `RESTRICT` | The change is rejected immediately. The check cannot be deferred. | Data that must never be orphaned or silently removed. |
| `CASCADE` | The same change is applied to the children: they are deleted, or their key is updated. | Rows that have no meaning without the parent. |
| `SET NULL` | The child's foreign key column becomes `NULL`. | Optional relationships. |
| `SET DEFAULT` | The child's foreign key column is set to its default value. | Rare. Needs a valid default parent row. |
NO ACTION and RESTRICT
Both refuse the change. The difference is timing. NO ACTION checks at the end of the statement, so a single statement that fixes things up can succeed. RESTRICT checks right away and never allows that. For a constraint that is not deferrable, the visible result is usually the same. Use RESTRICT when you want to state clearly in the schema that the rejection is intentional.
The earlier example in this tutorial relies on the default:
-- Fails while any order still references customer 1 (default NO ACTION)
DELETE FROM customers WHERE customer_id = 1;The error names the constraint and says the key is still referenced from the child table.
CASCADE
CASCADE propagates the change. With ON DELETE CASCADE, deleting a parent deletes all of its children. The order_items table is a good fit, because a line item has no meaning without its order.
CREATE TABLE products (
product_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE order_items (
order_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
PRIMARY KEY (order_id, product_id),
FOREIGN KEY (order_id) REFERENCES orders (order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products (product_id) ON DELETE RESTRICT
);Deleting an order now removes its items automatically. Deleting a product that appears on any order is refused, which protects the sales history.
Cascades chain. If order_items had its own children with ON DELETE CASCADE, they would be deleted too. One DELETE on a parent can therefore remove many rows across several tables.
SET NULL
SET NULL keeps the child row and clears its link. It requires the foreign key column to be nullable. The self-referencing employees table uses it:
CREATE TABLE employees (
employee_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
manager_id INTEGER REFERENCES employees (employee_id) ON DELETE SET NULL
);If a manager is deleted, their direct reports remain, and their manager_id becomes NULL. They now look like top-level employees. Decide whether that is acceptable, or whether you want a person to reassign them first.
If you declare SET NULL on a column that is NOT NULL, the delete fails at run time, because the database cannot store the NULL.
SET DEFAULT
SET DEFAULT sets the child column to its DEFAULT value. That value must itself reference an existing parent row, or the operation fails. A common pattern is a placeholder parent such as an "Unassigned" category with a known key. It is uncommon because the placeholder row must always exist.
Which action fits which relationship
Ask what the child means without its parent.
- The child is part of the parent. Use
CASCADE. Examples: order lines, invoice items, comments on a deleted post. - The child is a record you must keep. Use
RESTRICTorNO ACTION. Examples: orders for a customer, payments, audit rows. - The link is optional. Use
SET NULL. Examples: an employee's manager, a ticket's assignee. - There is a sensible fallback parent. Use
SET DEFAULT, sparingly.
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL
REFERENCES customers (customer_id)
ON DELETE RESTRICT
ON UPDATE CASCADE,
ordered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);Here a customer who has orders cannot be deleted, but if the customer's key ever changes, the orders follow.
ON UPDATE in practice
ON UPDATE CASCADE copies a changed parent key into every child row. It matters mostly for natural keys, which can change in the real world. A surrogate key such as customer_id should never change, so updates to it are rare and ON UPDATE rarely does anything.
Suppose a table of countries uses a natural key:
CREATE TABLE countries (
code CHAR(2) PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE cities (
city_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
country_code CHAR(2) NOT NULL
REFERENCES countries (code)
ON UPDATE CASCADE
);
INSERT INTO countries (code, name) VALUES ('XX', 'Test Land');
INSERT INTO cities (name, country_code) VALUES ('Sample City', 'XX');
UPDATE countries SET code = 'TL' WHERE code = 'XX';
SELECT name, country_code FROM cities;The final query returns Sample City with TL. Without ON UPDATE CASCADE, the UPDATE would be rejected.
A runnable demonstration
This script shows three of the actions side by side. Run it in an empty PostgreSQL database.
CREATE TABLE parents (
parent_id INTEGER PRIMARY KEY
);
CREATE TABLE kids_cascade (
kid_id INTEGER PRIMARY KEY,
parent_id INTEGER REFERENCES parents (parent_id) ON DELETE CASCADE
);
CREATE TABLE kids_setnull (
kid_id INTEGER PRIMARY KEY,
parent_id INTEGER REFERENCES parents (parent_id) ON DELETE SET NULL
);
CREATE TABLE kids_restrict (
kid_id INTEGER PRIMARY KEY,
parent_id INTEGER REFERENCES parents (parent_id) ON DELETE RESTRICT
);
INSERT INTO parents VALUES (1), (2);
INSERT INTO kids_cascade VALUES (10, 1);
INSERT INTO kids_setnull VALUES (20, 1);
-- Succeeds: the cascade child is deleted, the set-null child keeps its row.
DELETE FROM parents WHERE parent_id = 1;
SELECT count(*) AS cascade_rows FROM kids_cascade;
SELECT kid_id, parent_id FROM kids_setnull;
INSERT INTO kids_restrict VALUES (30, 2);
-- Fails: kids_restrict still references parent 2.
DELETE FROM parents WHERE parent_id = 2;The first select returns 0. The second returns kid 20 with a NULL parent. The last DELETE fails with a foreign key violation.
Edge cases and gotchas
- Cascades hide large deletes. A single
DELETEcan remove thousands of rows. Test cascades on a copy of the data, and be cautious withCASCADEon tables that hold financial or legal records. - Cascading deletes need an index on the child column. The database must find the children of the deleted parent. Without an index on the foreign key column, each parent delete scans the child table. See the chapter on indexing foreign keys.
- Triggers still fire. Rows removed by a cascade can fire delete triggers on the child table.
- Cycles are possible. Two tables that cascade to each other, or a chain that loops back, can behave in surprising ways. Keep cascade paths simple.
- SQL Server restricts cascade paths. It rejects schemas where multiple cascade paths reach the same table. MySQL's InnoDB engine enforces foreign keys. Older MyISAM tables parse but ignore them. Oracle supports
ON DELETE CASCADEandON DELETE SET NULLbut has noON UPDATEclause for foreign keys, so you must avoid changing parent keys there. - Changing an action later. You cannot alter a referential action in place. Drop the constraint and add it again with the new action (see the chapter on altering constraints).
Exercises
Exercise
A tickets table has assignee_id, a nullable foreign key to users (user_id). When a user leaves and their row is deleted, tickets must remain and become unassigned. Which ON DELETE action do you choose, and what must be true of the column?
Show answer
Use ON DELETE SET NULL. The assignee_id column must allow NULL. If it were declared NOT NULL, the delete would fail.
Exercise
You delete one row from orders. The order_items table references orders with ON DELETE CASCADE, and also references products with ON DELETE RESTRICT. What happens to the order's items, and to the products they refer to?
Show answer
The order's rows in order_items are deleted by the cascade. The products are untouched, because deleting an item row does not delete or change its parent product. The RESTRICT rule only matters if you try to delete a product that still appears in order_items.
Exercise
Why does ON UPDATE CASCADE rarely matter for a table with a generated surrogate primary key?
Show answer
Surrogate keys are generated values with no real-world meaning, so they are almost never changed. No parent key update happens, so the ON UPDATE action never runs. It matters more for natural keys such as country codes, which can change.