Postgres: duplicate key value violates unique constraint
A sequence is behind its table, or two writers raced and the index caught the loser. Read the constraint name, then reset or upsert.

Introduction & Quick Summary
ERROR: duplicate key value violates unique constraint "accounts_pkey"
DETAIL: Key (id)=(8f2c1a44-...) already exists.The row you tried to insert collides with an existing unique index. The constraint name in the message tells you which index, and the DETAIL line tells you which values, which is usually enough to identify whether the id, the natural key, or an unrelated column is fighting you.
Four realistic causes, in descending order of frequency:
- A sequence behind its table. After a
pg_restore, a data copy, or a manual insert with explicit ids, the sequence still points at an old value, so new inserts reuse ids. - A race, not a duplicate. Two transactions both
SELECTand find nothing, then bothINSERT. The unique index catches the loser, and the application reports it as a bug in the data. - An upsert that did not match the index.
ON CONFLICT (email)requires a unique index on exactlyemail; a unique index onlower(email)does not qualify. - Migrated data that was never deduplicated. Case differences, trailing spaces or time zones make values distinct in the source and equal in the target.
| Constraint in the message | Typical source | Usual fix |
|---|---|---|
*_pkey | Sequence out of sync | setval to max(id) |
*_key on a business column | Double submit or missing upsert | ON CONFLICT DO NOTHING |
| Partial unique index | WHERE deleted_at IS NULL | Match the index predicate |
| Foreign key named like unique | Actually a different error code | Read the SQLSTATE |
Core Mechanics, Signatures & Reproducible Setup
A unique index enforces uniqueness during insert and update, and the violation aborts the transaction with SQLSTATE 23505. Sequences are non-transactional: a rolled-back insert still consumes a value, and setval is the only way to realign one. ON CONFLICT turns the conflict into a no-op or an update, but only when the inference clause can identify a unique index; expressions and predicates must be spelled exactly.
Reproduce both failure modes:
CREATE TABLE accounts (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, email text UNIQUE);
INSERT INTO accounts (email) VALUES ('a@example.com');
INSERT INTO accounts (email) VALUES ('a@example.com');
-- ERROR: duplicate key value violates unique constraint "accounts_email_key"
INSERT INTO accounts (id, email) VALUES (1, 'b@example.com');
-- ERROR: duplicate key value violates unique constraint "accounts_pkey"The idempotent version of the same write:
INSERT INTO accounts (email) VALUES ('a@example.com')
ON CONFLICT (email) DO NOTHING;
INSERT INTO accounts (email) VALUES ('a@example.com')
ON CONFLICT (email) DO UPDATE
SET email = EXCLUDED.email
RETURNING id;Resetting a sequence after a restore:
SELECT setval(pg_get_serial_sequence('accounts', 'id'),
(SELECT COALESCE(MAX(id), 1) FROM accounts),
(SELECT COUNT(*) > 0 FROM accounts));Run the same query for every serial table after a restore rather than only the table that failed; the others are equally likely to be behind.
Key Comparison Table
| Approach | Duplicate behavior | Concurrency-safe | Loses sequence values |
|---|---|---|---|
INSERT alone | Raises 23505 | n/a | On rollback |
ON CONFLICT DO NOTHING | Silently skips | Yes | Yes |
ON CONFLICT DO UPDATE | Updates the row | Yes | Yes |
SELECT then INSERT | Race condition | No | Yes |
MERGE (Postgres 15+) | Configurable | Yes, with retries | Depends |
INSERT ... RETURNING with retry | Retries on 23505 | Yes, if bounded | Yes |
| Index shape | Inference clause | Works with ON CONFLICT |
|---|---|---|
UNIQUE (email) | (email) | Yes |
UNIQUE (lower(email)) | (lower(email)) | Yes, exact expression required |
UNIQUE (email) WHERE deleted_at IS NULL | (email) WHERE deleted_at IS NULL | Yes, predicate required |
UNIQUE USING INDEX | Column list | Yes |
| Exclusion constraint | Not supported | No |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: Sequence drift after COPY
COPY with explicit ids does not advance the sequence. Two statements fix it without downtime:
BEGIN;
LOCK TABLE accounts IN SHARE ROW EXCLUSIVE MODE;
SELECT setval(pg_get_serial_sequence('accounts', 'id'),
(SELECT MAX(id) FROM accounts));
COMMIT;The lock prevents a concurrent insert from taking a value between max and setval.
Case 2: A retry loop that hides real duplicates
for attempt in range(3):
try:
cur.execute("INSERT INTO accounts (email) VALUES (%s) RETURNING id", (email,))
break
except psycopg.errors.UniqueViolation:
cur.execute("SELECT id FROM accounts WHERE email = %s", (email,))
account_id = cur.fetchone()[0]
breakThis is correct only if a row is always expected to exist after the conflict. If the conflict came from a sequence, the retry loop will fail three times and mask the real cause, so log the constraint name.
Case 3: Partial unique indexes on soft deletes
CREATE UNIQUE INDEX accounts_email_active_key
ON accounts (email) WHERE deleted_at IS NULL;
INSERT INTO accounts (email, deleted_at) VALUES ('a@example.com', NULL)
ON CONFLICT (email) WHERE deleted_at IS NULL DO NOTHING;Omitting the WHERE clause from the inference produces there is no unique or exclusion constraint matching the ON CONFLICT specification, a different but related error.
Case 4: Case-insensitive uniqueness
Without a functional index, A@x.com and a@x.com are distinct rows. Add the index first, deduplicate existing data, then upsert against the same expression:
DELETE FROM accounts a USING accounts b
WHERE lower(a.email) = lower(b.email) AND a.id > b.id;
CREATE UNIQUE INDEX accounts_email_lower_key ON accounts (lower(email));
INSERT INTO accounts (email) VALUES ('A@x.com')
ON CONFLICT (lower(email)) DO NOTHING;Case 5: Bulk insert with duplicate rows inside the same statement
INSERT INTO tags (name) VALUES ('go'), ('rust'), ('go')
ON CONFLICT (name) DO NOTHING;ON CONFLICT handles duplicates within a single statement only for DO NOTHING; DO UPDATE raises ON CONFLICT DO UPDATE command cannot affect row a second time. Deduplicate with SELECT DISTINCT in the source query.
Case 6: serializable retries
Under SERIALIZABLE, concurrent upserts can still produce serialization failures rather than 23505. Both need retry logic, and treating a serialization failure as a duplicate is a common bug that silently drops writes.
Common Compilation/Runtime Mistakes & Version Gotchas
ON CONFLICTrequires a matching index, not a matching column. A plainUNIQUEindex on a different column set does not satisfy inference even if the values would be unique.- Bulk
COPYbypasses conflict handling. Postgres 17 has noCOPY ... ON CONFLICT; staging tables plusINSERT ... SELECT ... ON CONFLICTis the supported pattern. GENERATED ALWAYS AS IDENTITYrejects explicit ids. WithGENERATED BY DEFAULTthey are allowed, which is how restore paths create drift in the first place.- Sequence cache and rollback. A cached sequence with
CACHE 100jumps by 100 after a restart; ids are never reused, andsetvalmust account for the cache so the next value does not collide. - Constraint deferral. A
DEFERRABLE INITIALLY DEFERREDunique constraint reports the violation atCOMMIT, not at the statement, so the failing code is earlier than the error suggests. - Trigger-generated duplicates. A
BEFORE INSERTtrigger that inserts into the same table can produce a second row with the same natural key inside one statement, which fails against the index rather than the trigger.
If the conflicting payload comes from an API response, compare the two candidate rows field by field with the diff tool after dumping them as JSON, and use the JSON formatter to read the DETAIL payload when a driver wraps it in a structured error object. For schema review before adding the index, the SQL schema viewer highlights existing constraints so the migration does not create a redundant one. Ad-hoc queries belong in the SQL formatter when you need to hand them to a reviewer.
Primary references: INSERT ... ON CONFLICT documents inference clauses and the "cannot affect row a second time" rule, and sequence functions covers setval semantics and cache behavior.
Official references
primary documentationThe SQL documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related SQL guides
All SQL guidesSQLite: database is locked (SQLITE_BUSY) under concurrent writes
SQLite allows one writer. Set a busy timeout, switch to WAL, start write transactions as IMMEDIATE, and reduce to a single writer connection.
SQL Window Functions: ROW_NUMBER, RANK, DENSE_RANK, and LEAD/LAG Explained
How the four ranking and offset functions differ on ties, why the default RANGE frame makes running totals repeat, and how LAG builds gap-and-island.
Postgres: column does not exist (SQLSTATE 42703)
42703 means the identifier you wrote is not the one that exists. Check case folding, alias scope, search_path and migration drift.
PostgreSQL: canceling statement due to statement timeout
The statement was canceled by statement_timeout. Find whether the role, the pooler or the client set it, then scope a longer budget to that job.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.