On 1st of August Tom Lane committed patch from Itagaki Takahiro:
Improve unique-constraint-violation error messages to include the exact values being complained of. In passing, also remove the arbitrary length limitation in the similar error detail message for foreign key violations. Itagaki Takahiro
and later added an extension to it:
Department of second thoughts: let's show the exact key during unique index build failures, too. Refactor a bit more since that error message isn't spelled the same.
While it is not a super-complicated new feature, it's definitely useful to know why there is unique violation:
# create table test ( i int4 primary key ); NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "test_pkey" for table "test" CREATE TABLE
# insert into test (i) values (1); INSERT 0 1 # insert into test (i) values (2); INSERT 0 1 # insert into test (i) values (1); ERROR: duplicate key value violates unique constraint "test_pkey" DETAIL: Key (i)=(1) already exists.
Of course one can say that since we know constraint name, we can extract the value from SQL – that's true, but there are also multi-row inserts:
# insert into test (i) select generate_series(1,10); ERROR: duplicate key value violates unique constraint "test_pkey" DETAIL: Key (i)=(1) already exists.
It works the same way when we add index/constraint to existing table:
# create table test ( i int4 ); CREATE TABLE # insert into test (i) values (1), (2), (1), (3), (2), (4), (5); INSERT 0 7 # create unique index q on test (i); ERROR: could not create unique index "q" DETAIL: Key (i)=(2) is duplicated.
It is worth noting that only first violating value is reported – i.e. the fact that we fixed problem with value shown in DETAIL doesn't mean that the index can be created now.
To check for all duplicates you should use a bit more complex query:
# select i from test group by i having count(*) > 1; i --- 1 2 (2 rows)