Sub topic 12
Foreign keys and deleting parent rows
This chapter covers what happens when you delete or update a row that other rows depend on. It assumes you can write basic INSERT, UPDATE, and DELETE statements with a WHERE clause. It also assumes you know what a primary key and a foreign key are, and that you have the customers and orders tables from earlier in this tutorial.
Parents and children
A foreign key links a column in one table to the primary key of another. In the example schema, orders.customer_id references customers.id. The customers table is the parent and orders is the child.
The database enforces this link in two directions:
- Inserting or updating a child row fails if
customer_iddoes not match an existing parent row. - Deleting or updating a parent row is checked against the child rows that still point to it.
The first direction was covered in the chapter on constraint errors. This chapter covers the second.
The default behavior: refuse the change
Suppose Ada (customer 1) has an order, and you try to delete her.
INSERT INTO orders (id, customer_id, total)
VALUES (100, 1, 49.90);
DELETE FROM customers
WHERE id = 1;With the foreign key as defined in the example schema, the DELETE fails. If you use PostgreSQL, the message looks like this:
ERROR: update or delete on table "customers" violates foreign key constraint
"orders_customer_id_fkey" on table "orders"
DETAIL: Key (id)=(1) is still referenced from table "orders".The statement changes nothing. This is the default action, called NO ACTION. The database would rather reject your statement than leave an order that points to a customer who no longer exists. Such an order is called an orphan row.
The error is useful. It tells you that the data you are about to remove is still in use.
Option 1: delete the children first
The most explicit approach is to remove the dependent rows yourself, then the parent. Do both in one transaction so you never end up with half the work done.
BEGIN;
DELETE FROM orders
WHERE customer_id = 1;
DELETE FROM customers
WHERE id = 1;
COMMIT;The order matters. Deleting the parent first fails, because the children still reference it. Deleting the children first succeeds.
Use this approach when deleting a customer should be a deliberate act and you want to see exactly which rows go. You can run a SELECT COUNT(*) FROM orders WHERE customer_id = 1 first to preview the effect, as described in the chapter on previewing changes.
Option 2: declare an ON DELETE action
You can tell the database what to do when a parent row is deleted. The action is part of the foreign key definition.
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL
REFERENCES customers (id) ON DELETE CASCADE,
total NUMERIC(10, 2) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'new'
);The common actions are:
| Action | Effect when the parent row is deleted | Notes |
|---|---|---|
| `NO ACTION` | The statement fails if child rows exist. | The default. The check can be postponed in some databases until the end of the statement or transaction. |
| `RESTRICT` | The statement fails immediately if child rows exist. | Close to `NO ACTION`, but the check is never postponed. |
| `CASCADE` | The child rows are deleted too. | Convenient, and dangerous when chained across tables. |
| `SET NULL` | The child's foreign key column is set to `NULL`. | The column must allow `NULL`. |
| `SET DEFAULT` | The child's column is set to its default value. | Not supported by MySQL's InnoDB engine. |
ON UPDATE accepts the same actions. It controls what happens when the parent's key value changes. Primary keys rarely change, so you will see ON UPDATE much less often.
CASCADE in practice
With ON DELETE CASCADE in place, a single statement removes the parent and its children.
DELETE FROM customers
WHERE id = 1;The database also deletes every row in orders where customer_id = 1. If orders is itself the parent of an order_items table with ON DELETE CASCADE, those rows go too. The deletion follows the chain as far as it goes.
SET NULL in practice
SET NULL fits cases where the child row is still meaningful without its parent. For example, you might keep orders for accounting after a customer leaves. That requires customer_id to allow NULL, so the NOT NULL in the example schema would have to go.
CREATE TABLE orders_kept (
id INTEGER PRIMARY KEY,
customer_id INTEGER
REFERENCES customers (id) ON DELETE SET NULL,
total NUMERIC(10, 2) NOT NULL
);
INSERT INTO orders_kept (id, customer_id, total)
VALUES (1, 2, 15.00);
DELETE FROM customers
WHERE id = 2;
SELECT id, customer_id FROM orders_kept;After the delete, the SELECT returns the row with customer_id equal to NULL. If the column were declared NOT NULL, the delete would fail because SET NULL cannot be applied.
Choosing an approach
Pick the action by asking what the child row means without its parent.
- If the child is part of the parent, such as order lines inside an order,
CASCADEfits. - If the child is an independent record that merely refers to the parent, such as invoices that must be kept, use
RESTRICTorNO ACTIONand make deletion a deliberate step. - If the child should survive but the link can be dropped, use
SET NULL.
Many teams avoid physical deletes of important parent rows altogether. They add a status column, as customers has, and set it to 'inactive' with an UPDATE. The row stays, so no child is orphaned, and the history remains available.
Dialect differences and gotchas
- SQLite does not enforce foreign keys unless you run
PRAGMA foreign_keys = ON;on each connection. Without it, the delete in the first example succeeds and leaves orphans. - MySQL enforces foreign keys only in InnoDB tables. It rejects
SET DEFAULT, andNO ACTIONbehaves likeRESTRICT. - SQL Server does not allow some cascade paths. If two cascade routes from one parent reach the same child table, it refuses to create the constraint.
- PostgreSQL lets you declare a constraint as
DEFERRABLE, so the check runs atCOMMITrather than at each statement. This helps when rows must reference each other. - Adding the constraint later is done with
ALTER TABLE. The syntax differs slightly between systems, and the existing data must already satisfy the rule. - Indexes on the child column matter. Most databases index the primary key automatically but not the foreign key column. Without an index on
orders.customer_id, each parent delete must scan the whole child table to look for references.
Common mistakes
- Deleting the parent first inside a transaction, seeing the error, and then continuing the transaction. In PostgreSQL the transaction is now aborted, and you must
ROLLBACKbefore running anything else. - Adding
ON DELETE CASCADEto silence an error without thinking about what else it will remove. - Using
SET NULLon a column declaredNOT NULL. - Assuming SQLite is enforcing keys when the pragma was never set.
- Searching for orphans by hand after the fact. A query like the one below finds child rows with no matching parent.
SELECT o.id, o.customer_id
FROM orders AS o
LEFT JOIN customers AS c ON c.id = o.customer_id
WHERE c.id IS NULL;On a database with enforced foreign keys this query returns no rows. If it returns rows, the constraint is missing or was disabled while the data was loaded.
Exercise
The orders table was created with customer_id INTEGER NOT NULL REFERENCES customers (id) ON DELETE SET NULL. What happens when you delete a customer who has orders, and how would you fix the definition if you want the orders to be kept?
Show answer
The delete fails. SET NULL tries to write NULL into customer_id, but the column is NOT NULL, so the database rejects the statement and nothing changes. To keep orders after a customer is deleted, remove NOT NULL from customer_id so it can hold NULL. Keep ON DELETE SET NULL. Alternatively, keep the NOT NULL and use RESTRICT, then mark customers 'inactive' instead of deleting them.
Exercise
Customer 5 has three orders, and orders.customer_id references customers (id) with the default NO ACTION. Write the statements that delete the customer and the orders safely, and say why you wrap them in a transaction.
Show answer
BEGIN; DELETE FROM orders WHERE customer_id = 5; DELETE FROM customers WHERE id = 5; COMMIT; The children are deleted first because the parent delete would fail while orders still reference it. The transaction makes both deletes succeed or fail together, and it lets you run SELECT COUNT(*) checks and ROLLBACK before COMMIT if the counts look wrong.