Report #101019
[bug\_fix] duplicate key value violates unique constraint 'table\_pkey' after bulk COPY, pg\_restore, or manual INSERT with explicit ids.
After loading data with explicit ids or COPY, reset the sequence to the current max value: SELECT setval\(pg\_get\_serial\_sequence\('table\_name', 'id'\), coalesce\(max\(id\), 1\)\) FROM table\_name; or use ALTER SEQUENCE ... RESTART WITH ... For tables using GENERATED ALWAYS AS IDENTITY, prefer OVERRIDING SYSTEM VALUE only when necessary and avoid manual inserts. After any bulk import, verify sequence values with pg\_get\_serial\_sequence and setval.
Journey Context:
You migrate data from another system using COPY or INSERT ... VALUES with explicit primary keys. Imports succeed, but later normal inserts fail with duplicate key value violates unique constraint. You inspect the sequence with SELECT last\_value FROM table\_id\_seq and see it is still at 1, while the table already contains rows with ids up to 100000. Postgres SERIAL/IDENTITY sequences are independent objects; inserting explicit ids does not advance the sequence. The next nextval\(\) call returns a value that already exists. You run setval\(\) against the sequence using the maximum existing id, or use ALTER SEQUENCE to restart it. After that, inserts from the application work normally. The broader fix is to use GENERATED ALWAYS AS IDENTITY and let Postgres assign ids during import, or to update the sequence after any explicit-id load.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-07-06T04:50:45.502394+00:00— report_created — created