PostgreSQL error 23505 on a unique column that is not the primary key
Your error
ERROR: duplicate key value violates unique constraint "foo_code_key"2 more lines it can showFix it fast
Most common cause, 1 of 4The value is already stored and the code inserts it again
Decide what a repeat should do and say so in the statement: skip it with DO NOTHING, or refresh the stored row with DO UPDATE and the EXCLUDED values.
INSERT INTO customers (email, name)
VALUES ('ada@example.com', 'Ada')
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;Short answer
ERROR: duplicate key value violates unique constraint (SQLSTATE 23505) on a non-primary-key column means the row you insert or update would give a UNIQUE column a value another row already has. The DETAIL line names that key. Upsert with ON CONFLICT, remove duplicates inside the batch, or make the constraint DEFERRABLE for key-shifting updates. PostgreSQL 15 to 19.
Which cause do you have?
Take the name from the error and the key from the DETAIL line. The name belongs either to a UNIQUE constraint or to a unique index created on its own, so one of the first two queries shows the table and columns. Then look for the row that already holds the value.
SELECT conrelid::regclass AS table_name, pg_get_constraintdef(oid)
FROM pg_constraint WHERE conname = 'foo_code_key';
SELECT tablename, indexdef FROM pg_indexes WHERE indexname = 'foo_code_key';
-- with the table and value found above
SELECT * FROM foo WHERE code = 'A-100';Then find the line you see in this list and open its fix:
- 1The value is already stored and the code inserts it again
The SELECT finds an older row with the same value, and the failing INSERT has no ON CONFLICT clause - 2Two sessions checked for the value at the same moment, then both inserted
Errors appear only now and then under load, the code runs a SELECT check before every INSERT, and the stored row was created a moment before the failed request - 3One statement carries the same key twice
The table did not hold the value before, but the multi-row INSERT or INSERT ... SELECT contains it on two rows - 4An UPDATE shifts or swaps unique values between rows
The failing statement is an UPDATE such as SET position = position + 1, and the DETAIL key is a value that is free once the statement ends
What does the error look like?
ERROR: duplicate key value violates unique constraint "foo_code_key"DETAIL: Key (code)=(A-100) already exists.SQLSTATE 23505 (unique_violation)
Cause 1 of 4
The value is already stored and the code inserts it again
You seeThe SELECT finds an older row with the same value, and the failing INSERT has no ON CONFLICT clause
Check
Error 23505 here means the UNIQUE column already holds this value from an earlier run: a re-imported file, a job retried after a timeout, or a form submitted twice. Compare the timestamps or IDs of the existing row with the failed request to see which one it was.
SELECT * FROM foo WHERE code = 'A-100';Fix
Decide what a repeat should do and say so in the statement: skip it with DO NOTHING, or refresh the stored row with DO UPDATE and the EXCLUDED values.
INSERT INTO customers (email, name)
VALUES ('ada@example.com', 'Ada')
ON CONFLICT (email) DO UPDATE SET name = EXCLUDED.name;Verify
Running the same INSERT twice succeeds both times and leaves one row.
SELECT count(*) FROM customers WHERE email = 'ada@example.com';Confirmed by postgresql.org
Cause 2 of 4
Two sessions checked for the value at the same moment, then both inserted
You seeErrors appear only now and then under load, the code runs a SELECT check before every INSERT, and the stored row was created a moment before the failed request
Check
This 23505 comes from a check-then-insert pattern. Two transactions both run the SELECT, both see no row, and both INSERT; the unique index lets the first one in and rejects the second. The error is the constraint doing its job, and adding more checks in application code cannot close that gap.
SELECT id, created_at FROM signups WHERE email = 'ada@example.com';Fix
Drop the pre-check and let the database decide in one statement: INSERT ... ON CONFLICT guarantees an insert-or-update outcome even under high concurrency. Where an insert must fail on a repeat, catch SQLSTATE 23505 and report already exists instead of a server error.
INSERT INTO signups (email)
VALUES ('ada@example.com')
ON CONFLICT (email) DO NOTHING
RETURNING id; -- no row returned means it was already thereVerify
A load test that sends the same email from many parallel clients leaves one row and no 23505 in the logs.
SELECT email, count(*) FROM signups GROUP BY email HAVING count(*) > 1;Confirmed by postgresql.org
Cause 3 of 4
One statement carries the same key twice
You seeThe table did not hold the value before, but the multi-row INSERT or INSERT ... SELECT contains it on two rows
Check
When the stored data has no copy of the key, the duplicate is inside the statement itself: two rows of one batch collide with each other. Group the source data by the unique column to find the repeats.
SELECT code, count(*)
FROM staging_foo
GROUP BY code
HAVING count(*) > 1;Fix
Reduce the batch to one row per key before inserting, choosing which copy wins (here the newest). Do not lean on ON CONFLICT DO UPDATE for this: a batch that hits the same row twice fails with a cardinality error instead.
INSERT INTO foo (code, payload, updated_at)
SELECT DISTINCT ON (code) code, payload, updated_at
FROM staging_foo
ORDER BY code, updated_at DESC;Verify
The grouping query on the staging table returns no rows after cleanup, and the INSERT completes.
SELECT count(*), count(DISTINCT code) FROM foo;Confirmed by postgresql.org
Cause 4 of 4
An UPDATE shifts or swaps unique values between rows
You seeThe failing statement is an UPDATE such as SET position = position + 1, and the DETAIL key is a value that is free once the statement ends
Check
PostgreSQL checks a NOT DEFERRABLE unique constraint at each row, not at the end of the statement. Moving every position up by one therefore collides with the row that has not moved yet, even though the final result would be unique. The SQL standard checks at statement end instead.
SELECT conname, condeferrable
FROM pg_constraint
WHERE conname = 'items_position_key';Fix
Recreate the constraint as DEFERRABLE INITIALLY IMMEDIATE, which checks once the statement completes. Know the cost: the check can be much slower, and a deferrable constraint can no longer be the target of ON CONFLICT.
ALTER TABLE items
DROP CONSTRAINT items_position_key,
ADD CONSTRAINT items_position_key UNIQUE (position)
DEFERRABLE INITIALLY IMMEDIATE;Verify
condeferrable is now true and the shifting UPDATE runs without error.
UPDATE items SET position = position + 1;Confirmed by postgresql.org
How do I stop it coming back?
- Write every insert of user-supplied identifiers (emails, slugs, external IDs) as INSERT ... ON CONFLICT from the start.
- Map SQLSTATE 23505 to a clear already exists response in the API layer instead of a 500.
- Deduplicate import files in a staging table with a GROUP BY ... HAVING count(*) > 1 check before loading.
- Use DEFERRABLE only on constraints that need key-shifting updates, because it rules out ON CONFLICT on them.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.