Database Relationships and Diagrams · Lesson 21 of 112

Database Referential Integrity and ON DELETE

What you will learn

  • What referential integrity means
  • What happens by default when you delete a parent row
  • The rules RESTRICT, CASCADE and SET NULL
  • How ON UPDATE CASCADE works
  • How to choose a rule

1. The promise

Referential integrity is the promise that every foreign key value points to a row that really exists. Lesson 3.1 showed the database refusing an order for a customer who does not exist. The other half of the promise: what if you delete the customer who still has orders?

You must choose, and the database lets you state the choice in the foreign key with ON DELETE.

2. Four behaviours, one dataset

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). It creates small tables of its own in your browser's copy; run the examples from top to bottom, and press Reset data to start again.

First, the real data. Foreign keys are switched on, and the sample tables state no ON DELETE rule. Try to delete a parent row that still has children:

Customer 1 has orders:

DELETE FROM customers WHERE customer_id = 1;
IntegrityError: FOREIGN KEY constraint failed

Customer 1 has accounts:

DELETE FROM customers WHERE customer_id = 1;
IntegrityError: FOREIGN KEY constraint failed

Student 1 has enrollments:

DELETE FROM students WHERE student_id = 1;
IntegrityError: FOREIGN KEY constraint failed

The delete is refused, so no order or account or enrollment is left pointing at nothing. Now the same data shape with each rule in turn. The parent table has two rows, Rina (id 1) and Sam (id 2). The child table has three rows: two for Rina and one for Sam. We try to delete Rina under each rule.

No rule written (the default):

CREATE TABLE buyers_none (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE purchases_none (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES buyers_none (id), item TEXT);
INSERT INTO buyers_none VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO purchases_none VALUES (1, 1, 'Shirt'), (2, 1, 'Scarf'), (3, 2, 'Cap');
(3 rows changed)
DELETE FROM buyers_none WHERE id = 1;
IntegrityError: FOREIGN KEY constraint failed
CREATE TABLE holders_none (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE deposits_none (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES holders_none (id), item TEXT);
INSERT INTO holders_none VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO deposits_none VALUES (1, 1, 'Salary'), (2, 1, 'Gift'), (3, 2, 'Refund');
(3 rows changed)
DELETE FROM holders_none WHERE id = 1;
IntegrityError: FOREIGN KEY constraint failed
CREATE TABLE tutors_none (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sessions_none (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES tutors_none (id), item TEXT);
INSERT INTO tutors_none VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO sessions_none VALUES (1, 1, 'Algebra'), (2, 1, 'Poetry'), (3, 2, 'Violin');
(3 rows changed)
DELETE FROM tutors_none WHERE id = 1;
IntegrityError: FOREIGN KEY constraint failed

ON DELETE RESTRICT:

CREATE TABLE buyers_restrict (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE purchases_restrict (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES buyers_restrict (id) ON DELETE RESTRICT, item TEXT);
INSERT INTO buyers_restrict VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO purchases_restrict VALUES (1, 1, 'Shirt'), (2, 1, 'Scarf'), (3, 2, 'Cap');
(3 rows changed)
DELETE FROM buyers_restrict WHERE id = 1;
IntegrityError: FOREIGN KEY constraint failed
CREATE TABLE holders_restrict (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE deposits_restrict (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES holders_restrict (id) ON DELETE RESTRICT, item TEXT);
INSERT INTO holders_restrict VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO deposits_restrict VALUES (1, 1, 'Salary'), (2, 1, 'Gift'), (3, 2, 'Refund');
(3 rows changed)
DELETE FROM holders_restrict WHERE id = 1;
IntegrityError: FOREIGN KEY constraint failed
CREATE TABLE tutors_restrict (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sessions_restrict (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES tutors_restrict (id) ON DELETE RESTRICT, item TEXT);
INSERT INTO tutors_restrict VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO sessions_restrict VALUES (1, 1, 'Algebra'), (2, 1, 'Poetry'), (3, 2, 'Violin');
(3 rows changed)
DELETE FROM tutors_restrict WHERE id = 1;
IntegrityError: FOREIGN KEY constraint failed

ON DELETE CASCADE:

CREATE TABLE buyers_cascade (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE purchases_cascade (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES buyers_cascade (id) ON DELETE CASCADE, item TEXT);
INSERT INTO buyers_cascade VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO purchases_cascade VALUES (1, 1, 'Shirt'), (2, 1, 'Scarf'), (3, 2, 'Cap');
DELETE FROM buyers_cascade WHERE id = 1;
SELECT * FROM purchases_cascade ORDER BY id;
id  parent_id  item
--  ---------  ----
 3          2  Cap
(1 row)
CREATE TABLE holders_cascade (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE deposits_cascade (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES holders_cascade (id) ON DELETE CASCADE, item TEXT);
INSERT INTO holders_cascade VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO deposits_cascade VALUES (1, 1, 'Salary'), (2, 1, 'Gift'), (3, 2, 'Refund');
DELETE FROM holders_cascade WHERE id = 1;
SELECT * FROM deposits_cascade ORDER BY id;
id  parent_id  item
--  ---------  ------
 3          2  Refund
(1 row)
CREATE TABLE tutors_cascade (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sessions_cascade (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES tutors_cascade (id) ON DELETE CASCADE, item TEXT);
INSERT INTO tutors_cascade VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO sessions_cascade VALUES (1, 1, 'Algebra'), (2, 1, 'Poetry'), (3, 2, 'Violin');
DELETE FROM tutors_cascade WHERE id = 1;
SELECT * FROM sessions_cascade ORDER BY id;
id  parent_id  item
--  ---------  ------
 3          2  Violin
(1 row)

ON DELETE SET NULL:

CREATE TABLE buyers_setnull (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE purchases_setnull (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES buyers_setnull (id) ON DELETE SET NULL, item TEXT);
INSERT INTO buyers_setnull VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO purchases_setnull VALUES (1, 1, 'Shirt'), (2, 1, 'Scarf'), (3, 2, 'Cap');
DELETE FROM buyers_setnull WHERE id = 1;
SELECT * FROM purchases_setnull ORDER BY id;
id  parent_id  item
--  ---------  -----
 1       NULL  Shirt
 2       NULL  Scarf
 3          2  Cap
(3 rows)
CREATE TABLE holders_setnull (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE deposits_setnull (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES holders_setnull (id) ON DELETE SET NULL, item TEXT);
INSERT INTO holders_setnull VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO deposits_setnull VALUES (1, 1, 'Salary'), (2, 1, 'Gift'), (3, 2, 'Refund');
DELETE FROM holders_setnull WHERE id = 1;
SELECT * FROM deposits_setnull ORDER BY id;
id  parent_id  item
--  ---------  ------
 1       NULL  Salary
 2       NULL  Gift
 3          2  Refund
(3 rows)
CREATE TABLE tutors_setnull (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sessions_setnull (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES tutors_setnull (id) ON DELETE SET NULL, item TEXT);
INSERT INTO tutors_setnull VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO sessions_setnull VALUES (1, 1, 'Algebra'), (2, 1, 'Poetry'), (3, 2, 'Violin');
DELETE FROM tutors_setnull WHERE id = 1;
SELECT * FROM sessions_setnull ORDER BY id;
id  parent_id  item
--  ---------  -------
 1       NULL  Algebra
 2       NULL  Poetry
 3          2  Violin
(3 rows)
Rule What happens to Rina's child rows when Rina is deleted
(none written) in this SQLite run, the delete is refused
RESTRICT the delete is refused while child rows exist
CASCADE the child rows are deleted too
SET NULL the child rows stay but parent_id becomes NULL

(SET NULL only works if the column allows NULL; our column here had no NOT NULL.)

SQLite's documentation says that when no action is written, the default is NO ACTION. Two more actions exist.

SET DEFAULT puts the column's DEFAULT value into the children instead of NULL. Here every child row of a deleted parent moves to parent 2, because that is the default we declared:

CREATE TABLE buyers_setdef (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE purchases_setdef (id INTEGER PRIMARY KEY, parent_id INTEGER DEFAULT 2 REFERENCES buyers_setdef (id) ON DELETE SET DEFAULT, item TEXT);
INSERT INTO buyers_setdef VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO purchases_setdef VALUES (1, 1, 'Shirt'), (2, 1, 'Scarf'), (3, 2, 'Cap');
DELETE FROM buyers_setdef WHERE id = 1;
SELECT * FROM purchases_setdef ORDER BY id;
id  parent_id  item
--  ---------  -----
 1          2  Shirt
 2          2  Scarf
 3          2  Cap
(3 rows)
CREATE TABLE holders_setdef (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE deposits_setdef (id INTEGER PRIMARY KEY, parent_id INTEGER DEFAULT 2 REFERENCES holders_setdef (id) ON DELETE SET DEFAULT, item TEXT);
INSERT INTO holders_setdef VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO deposits_setdef VALUES (1, 1, 'Salary'), (2, 1, 'Gift'), (3, 2, 'Refund');
DELETE FROM holders_setdef WHERE id = 1;
SELECT * FROM deposits_setdef ORDER BY id;
id  parent_id  item
--  ---------  ------
 1          2  Salary
 2          2  Gift
 3          2  Refund
(3 rows)
CREATE TABLE tutors_setdef (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sessions_setdef (id INTEGER PRIMARY KEY, parent_id INTEGER DEFAULT 2 REFERENCES tutors_setdef (id) ON DELETE SET DEFAULT, item TEXT);
INSERT INTO tutors_setdef VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO sessions_setdef VALUES (1, 1, 'Algebra'), (2, 1, 'Poetry'), (3, 2, 'Violin');
DELETE FROM tutors_setdef WHERE id = 1;
SELECT * FROM sessions_setdef ORDER BY id;
id  parent_id  item
--  ---------  -------
 1          2  Algebra
 2          2  Poetry
 3          2  Violin
(3 rows)

Rina's rows now belong to Sam. That is rarely what a business wants, so SET DEFAULT is only sensible when the default is a harmless placeholder such as an "unknown" row.

NO ACTION versus RESTRICT. Both refuse the delete, but at different moments. RESTRICT refuses at once. NO ACTION waits until the end of the statement, and, if the foreign key is declared DEFERRABLE INITIALLY DEFERRED, until the transaction is committed, so you may delete the parent and then delete its children before committing. Here is the difference (transactions are the subject of chapter 6):

CREATE TABLE buyers_na (id INTEGER PRIMARY KEY);
CREATE TABLE purchases_na (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES buyers_na (id) ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED);
CREATE TABLE buyers_re (id INTEGER PRIMARY KEY);
CREATE TABLE purchases_re (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES buyers_re (id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED);
INSERT INTO buyers_na VALUES (1);
INSERT INTO buyers_re VALUES (1);
INSERT INTO purchases_na VALUES (1, 1);
INSERT INTO purchases_re VALUES (1, 1);
(1 row changed)

With NO ACTION the delete is accepted for now, and the commit succeeds once the children are gone:

BEGIN;
DELETE FROM buyers_na WHERE id = 1;
DELETE FROM purchases_na;
COMMIT;
(1 row changed)

With RESTRICT the delete is refused at once:

BEGIN;
(done)
DELETE FROM buyers_re WHERE id = 1;
IntegrityError: FOREIGN KEY constraint failed
ROLLBACK;
(done)
CREATE TABLE holders_na (id INTEGER PRIMARY KEY);
CREATE TABLE deposits_na (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES holders_na (id) ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED);
CREATE TABLE holders_re (id INTEGER PRIMARY KEY);
CREATE TABLE deposits_re (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES holders_re (id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED);
INSERT INTO holders_na VALUES (1);
INSERT INTO holders_re VALUES (1);
INSERT INTO deposits_na VALUES (1, 1);
INSERT INTO deposits_re VALUES (1, 1);
(1 row changed)

With NO ACTION the delete is accepted for now, and the commit succeeds once the children are gone:

BEGIN;
DELETE FROM holders_na WHERE id = 1;
DELETE FROM deposits_na;
COMMIT;
(1 row changed)

With RESTRICT the delete is refused at once:

BEGIN;
(done)
DELETE FROM holders_re WHERE id = 1;
IntegrityError: FOREIGN KEY constraint failed
ROLLBACK;
(done)
CREATE TABLE tutors_na (id INTEGER PRIMARY KEY);
CREATE TABLE sessions_na (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES tutors_na (id) ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED);
CREATE TABLE tutors_re (id INTEGER PRIMARY KEY);
CREATE TABLE sessions_re (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES tutors_re (id) ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED);
INSERT INTO tutors_na VALUES (1);
INSERT INTO tutors_re VALUES (1);
INSERT INTO sessions_na VALUES (1, 1);
INSERT INTO sessions_re VALUES (1, 1);
(1 row changed)

With NO ACTION the delete is accepted for now, and the commit succeeds once the children are gone:

BEGIN;
DELETE FROM tutors_na WHERE id = 1;
DELETE FROM sessions_na;
COMMIT;
(1 row changed)

With RESTRICT the delete is refused at once:

BEGIN;
(done)
DELETE FROM tutors_re WHERE id = 1;
IntegrityError: FOREIGN KEY constraint failed
ROLLBACK;
(done)

For everyday work, remember only this: with no action written, SQLite refuses a delete that would leave orphans.

3. Updating a key

ON UPDATE works the same way. Changing a parent's id with ON UPDATE CASCADE carries the new value to the children:

CREATE TABLE buyers_upd (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE purchases_upd (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES buyers_upd (id) ON UPDATE CASCADE, item TEXT);
INSERT INTO buyers_upd VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO purchases_upd VALUES (1, 1, 'Shirt'), (2, 1, 'Scarf'), (3, 2, 'Cap');
UPDATE buyers_upd SET id = 10 WHERE id = 1;
SELECT * FROM purchases_upd ORDER BY id;
id  parent_id  item
--  ---------  -----
 1         10  Shirt
 2         10  Scarf
 3          2  Cap
(3 rows)
CREATE TABLE holders_upd (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE deposits_upd (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES holders_upd (id) ON UPDATE CASCADE, item TEXT);
INSERT INTO holders_upd VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO deposits_upd VALUES (1, 1, 'Salary'), (2, 1, 'Gift'), (3, 2, 'Refund');
UPDATE holders_upd SET id = 10 WHERE id = 1;
SELECT * FROM deposits_upd ORDER BY id;
id  parent_id  item
--  ---------  ------
 1         10  Salary
 2         10  Gift
 3          2  Refund
(3 rows)
CREATE TABLE tutors_upd (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE sessions_upd (id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES tutors_upd (id) ON UPDATE CASCADE, item TEXT);
INSERT INTO tutors_upd VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO sessions_upd VALUES (1, 1, 'Algebra'), (2, 1, 'Poetry'), (3, 2, 'Violin');
UPDATE tutors_upd SET id = 10 WHERE id = 1;
SELECT * FROM sessions_upd ORDER BY id;
id  parent_id  item
--  ---------  -------
 1         10  Algebra
 2         10  Poetry
 3          2  Violin
(3 rows)

Primary keys rarely change, so this is seldom needed.

4. Choosing a rule

Situation Sensible rule
Orders must never lose their customer (money records) RESTRICT (refuse), or better, mark the customer inactive instead of deleting
Rows that make no sense alone (a profile, order lines of a deleted order) CASCADE
The link is optional and history should stay SET NULL

CASCADE is powerful and dangerous: one delete can remove many rows across tables. Use it only where the children truly belong to the parent.

Worked example: choosing rules for a blog

Tables: authors, posts(author_id), comments(post_id).

Link Rule Reason
comments.post_id to posts CASCADE a comment has no meaning without its post
posts.author_id to authors RESTRICT do not lose posts by deleting an author; the owner must decide first

These choices are one reasonable design, not the only one. Names are made up.

Common mistakes

  • Using CASCADE everywhere, then deleting far more than intended.
  • Using SET NULL on a NOT NULL column, which cannot work.
  • Relying on a default you did not check. State the rule you want.
  • Forgetting that foreign keys must be switched on in SQLite (lesson 3.1).

Key takeaways

  • Referential integrity: every foreign key points to a real row.
  • Deleting a parent can be refused (RESTRICT), can delete children (CASCADE), or can empty the link (SET NULL).
  • ON UPDATE CASCADE passes a changed key to the children.
  • Choose by what the children mean without the parent.
  • Prefer marking records inactive over deleting important ones.

Practice

1. What does ON DELETE CASCADE do?

Show answer

Deleting the parent row also deletes its child rows.

2. In the lesson's run, what happened with no rule written?

Show answer

The delete was refused with FOREIGN KEY constraint failed.

3. What do the orders look like after SET NULL?

Show answer

They remain, with customer_id set to None/NULL.

4. Which rule fits order lines belonging to an order?

Show answer

CASCADE, because the lines mean nothing without their order.

5. Why is CASCADE risky?

Show answer

One delete can silently remove many rows, possibly across several tables.

6. A blog has comments(post_id REFERENCES posts(id) ON DELETE CASCADE). An editor deletes a post that has 40 comments. How many comments are left for that post, and what would have happened with RESTRICT?

Show answer

None are left: the cascade deletes all 40 comments with the post. With RESTRICT, the delete of the post would have been refused while any of its comments existed.