I have an existing table in a Postgres database that accumulated duplicate values. We've cleared the table and repopulated the values, but want to prevent duplicates from occurring again. Thus we need a to add a constraint.
Table name: camembert
, sample data:
| handle | id | num |
| ------ | --- | ----- |
| 259 | 869 | AC003 |
| 259 | 869 | AC003 |
| 259 | 869 | AC003 |
| 259 | 856 | AC005 |
| 259 | 856 | AC005 |
| 259 | 856 | AC005 |
etc.
Below is an example of the issue (we actually have triplicates of everything)
The constraint should allow the first two columns to have duplicate values, however, the third column is the differentiator that makes the row unique. For example, when the table is properly populated it looks as follows:
| handle | id | num |
| ------ | ----- | ----- |
| 259 | 869 | AC003 |
| 259 | 856 | AC005 |
| 259 | 856 | AC007 |
| 47138 | 41085 | AC003 |
| 47138 | 41085 | AC005 |
| 47138 | 43513 | AC007 |
I attempted the following script:
ALTER TABLE camembert ADD CONSTRAINT num_uniq UNIQUE (num);
But got an error:
ERROR: could not create unique index "num" Detail: Key (num)=(AC003) is duplicated.
What am I misunderstanding about the unique constraint? What's the key statement to unlock this puzzle?