Referential actions: choose relationship lifecycle rules
Overview
Referential actions define what happens to dependent rows when a referenced key changes or is deleted. CASCADE propagates a change, SET NULL removes the reference, SET DEFAULT assigns the declared default, and NO ACTION or RESTRICT can reject the operation. Run each script separately in a fresh disposable SQLite database with PRAGMA foreign_keys=ON before BEGIN.
First example
CREATE TABLE draft_order (id INTEGER PRIMARY KEY);CREATE TABLE draft_line (id INTEGER PRIMARY KEY, order_id INTEGER REFERENCES draft_order(id) ON DELETE CASCADE);INSERT INTO draft_order VALUES (1),(2);INSERT INTO draft_line VALUES (10,1),(11,1),(12,2);DELETE FROM draft_order WHERE id=1;SELECT * FROM draft_line ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 12, 2 ]]How it works
Choose actions based on ownership and retention policy. Order lines might be dependent on a disposable draft order, while financial records may need preservation. SET NULL requires nullable child columns; SET DEFAULT must still satisfy the foreign key. NO ACTION can allow deferred checking when configured; RESTRICT blocks the relevant parent operation immediately in SQLite even for deferred foreign keys. ON UPDATE CASCADE changes referencing values when the parent key changes.
Practical example
CREATE TABLE team (id INTEGER PRIMARY KEY);CREATE TABLE worker (id INTEGER PRIMARY KEY, team_id INTEGER REFERENCES team(id) ON DELETE SET NULL ON UPDATE CASCADE);INSERT INTO team VALUES (1),(2);INSERT INTO worker VALUES (10,1),(11,2);UPDATE team SET id=3 WHERE id=2;DELETE FROM team WHERE id=1;SELECT * FROM worker ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 10, null ], [ 11, 3 ]]Practice and mistakes
Practice: predict the remaining child rows before running each DELETE. Try SET NULL with a NOT NULL child column in a new disposable database and explain the error. Never experiment with cascading deletion in production; inspect dependent rows and plan recovery first.