Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readSQL
#PostgreSQL#Indexes#Constraints#Data Integrity
Two identical row crates colliding at a cyan unique index gate, an amber sequence counter lagging behind

Introduction & Quick Summary

text
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 SELECT and find nothing, then both INSERT. 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 exactly email; a unique index on lower(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 messageTypical sourceUsual fix
*_pkeySequence out of syncsetval to max(id)
*_key on a business columnDouble submit or missing upsertON CONFLICT DO NOTHING
Partial unique indexWHERE deleted_at IS NULLMatch the index predicate
Foreign key named like uniqueActually a different error codeRead 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

ApproachDuplicate behaviorConcurrency-safeLoses sequence values
INSERT aloneRaises 23505n/aOn rollback
ON CONFLICT DO NOTHINGSilently skipsYesYes
ON CONFLICT DO UPDATEUpdates the rowYesYes
SELECT then INSERTRace conditionNoYes
MERGE (Postgres 15+)ConfigurableYes, with retriesDepends
INSERT ... RETURNING with retryRetries on 23505Yes, if boundedYes
Index shapeInference clauseWorks 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 NULLYes, predicate required
UNIQUE USING INDEXColumn listYes
Exclusion constraintNot supportedNo

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

python
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] break

This 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 CONFLICT requires a matching index, not a matching column. A plain UNIQUE index on a different column set does not satisfy inference even if the values would be unique.
  • Bulk COPY bypasses conflict handling. Postgres 17 has no COPY ... ON CONFLICT; staging tables plus INSERT ... SELECT ... ON CONFLICT is the supported pattern.
  • GENERATED ALWAYS AS IDENTITY rejects explicit ids. With GENERATED BY DEFAULT they are allowed, which is how restore paths create drift in the first place.
  • Sequence cache and rollback. A cached sequence with CACHE 100 jumps by 100 after a restart; ids are never reused, and setval must account for the cache so the next value does not collide.
  • Constraint deferral. A DEFERRABLE INITIALLY DEFERRED unique constraint reports the violation at COMMIT, not at the statement, so the failing code is earlier than the error suggests.
  • Trigger-generated duplicates. A BEFORE INSERT trigger 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 documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.