How should SQLite represent many-to-many relationships?
Quick answer
Represent each side as its own table, then add a junction table with one row per pair of related records. Put a foreign key in the junction table for each side, and use a composite primary key on the two foreign-key columns to prevent the same pair appearing twice. In SQLite, enable foreign-key enforcement separately on each connection with PRAGMA foreign_keys = ON. [S1]
The question, the details, the next step.
A practical checklist
Create one table for each entity, with a key for that entity.
Create a junction table with one column referencing each entity key.
Use
NOT NULLwhen every relationship must include both sides.Use a composite primary key on the pair when duplicate pairs should be disallowed.
Enable
PRAGMA foreign_keys = ONon each connection that should enforce the references.Check that each referenced parent key is a primary key or collectively unique.
A few more useful answers
Why not put several course IDs in one student column?
A junction table gives each student-course association its own row, with a separate reference to each entity. It also gives the pair a clear place to enforce uniqueness.
Does the composite primary key replace the foreign keys?
No. The composite primary key prevents duplicate pairs; the foreign keys express which parent rows the IDs refer to. They serve different purposes.
Does the schema decide what happens when a parent row is removed?
No removal behavior is specified here. Choose that rule for your application and define it deliberately; the cited SQLite guidance does not determine the right choice for your entities.
Sources
References used for this guide.
- [S1] SQLite Foreign Key Support: parent and child keys sqlite.org · Checked
