How can SQLite prevent duplicate combinations of column values?
Quick answer
Add a table-level UNIQUE(person_id, project_id) constraint. It makes the pair unique, so the same person can appear with different projects and the same project with different people. Do not put a separate UNIQUE constraint on each column: that would require every person and every project to appear at most once, which is a stricter, different rule. [S1]
The question, the details, the next step.
A practical checklist
Write the rule as: “No two rows may have the same person-and-project pair.”
Use one table-level
UNIQUE (person_id, project_id)constraint.Do not use separate
UNIQUEconstraints on the two columns unless each value must appear at most once.Check that different pairs sharing a person or a project should remain allowed.
Review existing rows and your table’s other requirements before applying a schema change.
A few more useful answers
Does the order of the two columns change which pair is constrained?
The columns correspond by position: (12, 45) and (45, 12) are different combinations when the first value is in person_id and the second is in project_id. The constraint makes the specified combination unique; it does not make each column individually unique. [S1]
Can I use this for a different kind of combination?
Yes. Apply the same design pattern to the set of columns that together define the duplicate you want to prevent. Make sure the rule is about the combination, not about each column appearing only once.
Does this example describe how to change a table that already exists?
No. It shows a disposable CREATE TABLE example. The cited SQLite material supports the constraint behavior, but does not establish a migration procedure for an existing table.
Sources
References used for this guide.
- [S1] SQLite CREATE TABLE: table constraints and UNIQUE sqlite.org · Checked
