You imported data, restored a table, or copied rows from another database. Now every insert from the application fails:
ERROR: duplicate key value violates unique constraint "users_pkey"
DETAIL: Key (id)=(1) already exists.
The next insert fails with id=2, then id=3... The table is fine. Its sequence is out of sync.
Why it happens
A serial, bigserial or GENERATED … AS IDENTITY column gets its default from a sequence, a separate counter object. The sequence only advances when it hands out a value (nextval()).
If rows were inserted with explicit ids, the sequence never sees them:
COPYorINSERTwith theidcolumn included (CSV imports,pg_dump --insertsof a single table, ETL tools);- data migrated from MySQL, SQL Server or another Postgres database;
- someone "fixing" data by hand with explicit ids.
The table now contains ids 1–50,000, but the sequence still says the next value is 1. Every default insert collides until the sequence passes the highest existing id.
(A full pg_dump/pg_restore includes setval() calls, so it doesn't have this problem. It's partial and custom loads that do.)
Check it
SELECT max(id) FROM users;
SELECT pg_get_serial_sequence('users', 'id'); -- e.g. public.users_id_seq
SELECT last_value, is_called FROM public.users_id_seq;
If last_value is lower than max(id), that's the problem.
Fix one table
SELECT setval(
pg_get_serial_sequence(, ),
(( (id) users), ) ,
);
