How do SQLite foreign keys connect child rows to parent rows?
Quick answer
A foreign key is a REFERENCES constraint on a child table’s column or columns. It points to named column(s) in a parent table; those parent columns must be a primary key or have a qualifying UNIQUE constraint or index. A child reference is valid when its value matches the parent key under SQLite’s comparison rules. If any child-key column is NULL, a matching parent row is not required.
The question, the details, the next step.
A practical checklist
Put the REFERENCES constraint on the child table’s intended foreign-key column or columns.
Name the parent table and its named key columns; do not use rowid as the parent key.
Confirm the parent columns form a primary key or have a qualifying UNIQUE constraint or unique index.
Decide whether NULL is an acceptable child-key value; use NOT NULL if every child must name a parent.
Use sample values to distinguish a matching parent key from a value with no corresponding parent.
A few more useful answers
Can a foreign key refer to a parent column that is not the primary key?
Yes, if the referenced parent columns collectively have a qualifying UNIQUE constraint or unique index. The parent key must be named columns, not rowid. [S1]
Does a NULL child key need a matching parent row?
No. If any column in the child key is NULL, SQLite does not require a corresponding parent row. [S1]
Does this relationship tell me how to display a task with its project?
No. A foreign key describes the schema relationship and reference condition; this guide does not provide a retrieval-query pattern.
Sources
References used for this guide.
- [S1] SQLite foreign keys: child keys, parent keys, and valid references sqlite.org · Checked
