How should SQLite foreign keys handle a deleted parent row?
Quick answer
Choose the foreign-key action according to what should happen to dependent child rows: use RESTRICT to prevent deleting a parent while those rows exist, CASCADE to delete them too, or SET NULL to keep them but clear their reference. These actions go on the child table’s REFERENCES constraint. SET NULL requires a child foreign-key column that accepts NULL. Test the selected behavior using disposable sample data. [S1]
The question, the details, the next step.
A practical checklist
Write down the intended child-row outcome before selecting an action.
Put the ON DELETE action on the child table’s REFERENCES constraint.
If selecting SET NULL, make sure the child foreign-key column can hold NULL.
Test parent deletion with dependent rows using disposable sample data.
Inspect the child table afterward and compare it with the intended outcome.
A few more useful answers
Where does SQLite’s ON DELETE action go?
It is specified on the child-table REFERENCES constraint. [S1]
Can I use SET NULL if the child foreign-key column is NOT NULL?
No: SET NULL requires a child column that can hold NULL. [S1]
Does CASCADE keep the child rows?
No. SQLite documents CASCADE as deleting dependent child rows when the parent is deleted. [S1]
Sources
References used for this guide.
- [S1] SQLite Foreign Key Support: ON DELETE actions sqlite.org · Checked
