How can a SQLite schema represent an optional relationship?
Quick answer
Represent an optional parent relationship with a child-table foreign-key column that permits NULL, such as project_id INTEGER REFERENCES project(id). In SQLite, NULL satisfies the foreign key; a non-NULL value must match a parent key. [S1] Choose a delete action based on what should happen when that parent is deleted: SET NULL preserves the child without the relationship, while other actions have different effects. Check that foreign-key enforcement is enabled in your application; the schema alone does not establish that it is. [S1]
The question, the details, the next step.
A practical checklist
Decide whether a child row can validly exist without its parent.
Use a nullable foreign-key column only when that absent relationship is allowed.
Choose the parent-deletion outcome deliberately; use
SET NULLwhen children should remain unassigned.Check that the result of the delete action satisfies the column’s other constraints.
Verify foreign-key enforcement and test NULL, matching-parent, missing-parent, and deletion cases in the application environment.
A few more useful answers
Does a NULL foreign key refer to a parent row?
No. In SQLite, a NULL child key satisfies the foreign key without requiring a matching parent; a non-NULL child key must match a parent key. [S1]
Does `ON DELETE SET NULL` delete the child row?
No. It sets the child key to NULL when a referenced parent is deleted, so the child remains without that relationship. The resulting value must satisfy the schema’s other constraints and foreign-key rules. [S1]
Does declaring a foreign key prove that enforcement is enabled?
No. The cited SQLite documentation does not establish that enforcement is enabled in every application or connection. [S1] Check the environment that uses your database.
Sources
References used for this guide.
- [S1] SQLite Foreign Key Support sqlite.org · Checked
