PostgreSQL "duplicate key value violates unique constraint" — Why Sequences Drift
Root cause of duplicate key violations after restore or bulk migration, one-line setval repair, and an automated schema-wide PL/pgSQL DO block.
Operational Verification & Reliability Metadata
The error string is a symptom, not the root cause. Do not restart the server blindly. Run the diagnostic queries below to pinpoint the actual failure mode.
▸Symptom
ERROR: duplicate key value violates unique constraint "users_pkey"
DETAIL: Key (id)=(1043) already exists.Occurs when a sequence is not advanced following a restore or explicit primary key insert.
▸Single Table Repair
SELECT setval(
pg_get_serial_sequence('public.users', 'id'),
(SELECT max(id) FROM public.users)
);- •PostgreSQL First Restore Drill Runbook
- •PostgreSQL Backup & Restore CheatSheet
- •Validated versions: PostgreSQL 14 / 15 / 16 / 17
Other Database Error Triage Playbooks
Other battle-tested diagnostic guides for high-severity database errors.
PostgreSQL too many clients already: 6-Step Resolution
Three root causes of FATAL: sorry, too many clients already, single diagnostic query to identify the cause, and permanent mitigation via max_connections and PgBouncer.
PostgreSQL password authentication failed: Root Cause and Fix
Four root causes of psql password authentication failed: incorrect password, md5/SCRAM mismatch, pg_hba.conf rule ordering, and port/cluster confusion. Step-by-step triage.
PostgreSQL connection refused: 8-Step Definitive Triage
Difference between connection refused, timeout, and no pg_hba entry; triage for listen_addresses, port conflicts, firewalls, and Docker container mappings.