About this article: This article is reviewed against the cited sources. This is source research, not lab validation. Check the stated versions and your own requirements before making changes.
PostgreSQL raises ERROR: duplicate key value violates unique constraint "orders_pkey" with the detail Key (id)=(1501) already exists. when an insert would repeat a value that a unique index already holds. When every ordinary insert fails on the id column right after a data load, a manual insert or a switch to a replica, a common cause is that the sequence feeding the column is behind the highest id in the table. Compare the two numbers, then move the sequence past the maximum.
What the error means
The error carries SQLSTATE 23505, named unique_violation in Appendix A. In PostgreSQL 17 source (tag REL_17_9), the index code builds the text duplicate key value violates unique constraint "%s" with the index name, and a detail line Key %s already exists.. Another source file, genam.c, documents the key text as the form "(key_name, ...)=(key_value, ...)". That is our reading of the code, not wording from the manual.
A sequence is the object behind a serial column or an identity column. The manual says nextval "Advances the sequence object to its next value and returns that value", and that this is done atomically, so concurrent sessions each get a distinct value. A sequence knows nothing about the rows in the table. If rows arrive with ids that the sequence did not hand out, it will eventually offer one that is taken.
Two facts from the manual shape the repair:
nextvalvalues are not given back: the manual says the value obtained "is not reclaimed for re-use if the calling transaction later aborts". Changes made bysetvalare likewise "not undone if the calling transaction rolls back". Each failed attempt moves the sequence on by one (our reading of those two statements), so the failures stop by themselves only once the sequence has passed the highest id, which can mean a long run of errors first.- With the two-parameter form of
setval, "the next nextval will advance the sequence before returning a value". With the three-parameter form andfalse, "the next nextval will return exactly the specified value".
Likely causes
| Cause | What you see | How to confirm |
|---|---|---|
| Rows loaded with explicit ids (CSV or COPY, an INSERT script, a migration) | Plain inserts fail on the primary key, and the key in the message is far below max(id) |
The sequence value is lower than max(id) |
| A logical replication subscriber that became the primary | First inserts after the switch fail | The manual says "Sequence data is not replicated", so the subscriber's sequence still shows its start value |
| A restore or copy that carried the table data but not the sequence value | Same as the first row, right after a restore | Compare the sequence with max(id) in the restored database |
| The application supplies its own ids for some rows | Only some inserts fail | The failing key matches an id the application chose |
| A real repeat of a business key (an email, a reference number) | The constraint name is not the primary key, and the key columns are not id |
Read the constraint and key in the message |
| Two requests choose the highest id plus one at the same moment | Rare, intermittent failures | The application selects max(id) and adds one |
Prove the cause before changing anything
Everything here only reads.
1. Read the whole message. Note the constraint name and the Key (...)=(...) detail. If the key columns are not the sequence-fed id, stop: the data really repeats, and the sequence is not the cause.
2. Find the sequence behind the column. The manual says pg_get_serial_sequence returns "the name of the sequence associated with a column, or NULL if no sequence is associated with the column".
SELECT pg_get_serial_sequence('public.orders', 'id');
A result of NULL means no sequence is attached. The id comes from somewhere else, such as application code or a column default that calls nextval directly.
3. Read the highest id in the table.
SELECT max(id) FROM public.orders;
4. Read where the sequence stands. The pg_sequences view lists last_value, described as "The last sequence value written to disk", and notes that with caching it "can be greater than the last value handed out from the sequence". It reads as null if the sequence "has not been read from yet".
SELECT sequencename, last_value FROM pg_sequences WHERE schemaname = 'public' AND sequencename = 'orders_id_seq';
Use the sequence name from step 2 (without the schema part). Avoid currval for this check: the manual says it raises an error if nextval has never been called in this session.
A good result is last_value at or above max(id). A bad result is last_value below max(id): the sequence will offer values the table already holds.
5. Check that the failing key exists.
SELECT id FROM public.orders WHERE id = 1501;
One row confirms that the sequence handed out a taken id. Use the key from your own message.
Fix
The repair sets the sequence past the highest id. The manual's example SELECT setval('myseq', 42, false); is annotated "Next nextval will return 42". Setting the value to max(id) + 1 with false means the next insert gets exactly the first unused number.
First save the current state:
psql -d appdb -c "SELECT sequencename, start_value, last_value FROM pg_sequences WHERE schemaname = 'public' AND sequencename = 'orders_id_seq'" -o orders_id_seq-before.txt
Risk: the next statement sets the current value of the sequence public.orders_id_seq. The sequence change takes effect at once and is not undone if the transaction around it rolls back. Set too low, inserts keep failing with 23505. Set above an id another system expects to receive next, ids are skipped, which leaves a gap. Gaps are normal: the manual says "PostgreSQL sequence objects cannot be used to obtain “gapless” sequences".
Run the statement once, for the one sequence found in step 2:
SELECT setval('public.orders_id_seq', (SELECT COALESCE(MAX(id), 0) + 1 FROM public.orders), false);
On an empty table COALESCE gives 0, so the value is 1 and the next insert gets 1.
Only if you need to back out: either undo statement sets the sequence back, so ids already issued after the repair are issued again. Read the saved values in orders_id_seq-before.txt, run only the one statement that applies to what the file shows, then repeat step 4.
Risk: the setval statement below sets the sequence public.orders_id_seq back to the value saved before the repair. Ids already issued after the repair are issued again, and the 23505 errors return for any id the table holds. This setval takes effect at once and is not undone if the transaction around it rolls back.
If the saved last_value is a number, use the three-parameter form of setval that the manual describes, with true, so that the next nextval returns the number after the saved one. Replace 1500 with your saved last_value:
SELECT setval('public.orders_id_seq', 1500, true);
If the saved last_value is null, the pg_sequences page gives three reasons: the sequence "has not been read from yet", the current user lacks USAGE or SELECT privilege, or the sequence is unlogged on a standby. Our own reading: when the sequence had not been read from, ALTER SEQUENCE ... RESTART with no value returns it to the recorded start value, which the first command also saved. The manual says this is "equivalent to supplying the start value that was recorded by CREATE SEQUENCE or last set by ALTER SEQUENCE START WITH".
Risk: the next statement is not a setval. The ALTER SEQUENCE page says it "blocks concurrent nextval, currval, lastval, and setval calls", and that a RESTART "is transactional", so it holds that block until its transaction ends and is rolled back with the transaction. On a running application, inserts that need a value from this sequence wait until then. It also puts the sequence back at its start value, so ids already issued after the repair are issued again. Run it only after you have ruled out the privilege and standby reasons.
ALTER SEQUENCE public.orders_id_seq RESTART;
Example (illustrative): On db01, a migration copied the orders table into appdb from a CSV file with its ids. The table now holds ids up to 48210 (max(id)), and the sequence orders_id_seq was never advanced, so last_value is 1500. The application on app01 gets duplicate key value violates unique constraint "orders_pkey" with Key (id)=(1501) already exists., because id 1501 is in the table. Each retry consumes another value (1502, 1503, and so on), and each fails, until a value above 48210 would come up. The administrator saves the sequence, then runs setval with 48210 + 1 = 48211 and false. The next insert gets id 48211.
Two variations the manual supports. After a logical replication switchover, the same page says the sequences must be updated "either by copying the current data from the publisher (perhaps using pg_dump) or by determining a sufficiently high value from the tables themselves". The query above is the second method. ALTER SEQUENCE ... RESTART WITH sets the same current value, but the manual says RESTART is transactional and "blocks concurrent transactions from obtaining numbers from the same sequence", so setval is the choice when the application is running.
If several tables were loaded, each sequence is a separate run of prove steps 2 to 4 and of the whole fix above, with its own save, warning and undo. A loop that sets every sequence in the database in one go skips the reading of each result (our own advice).
Confirm the fix
- Insert one row through the application, or a test insert. A test insert uses up id 48211 in the example for good (our own reading:
nextvalvalues are not given back), so the next real insert gets 48212; delete only a row that you created yourself. The insert must succeed with the id you expect. After the example'ssetvalwithfalse, that is 48211, which is the manual's "next nextval will return exactly the specified value" case. - Repeat step 4 of the checks, the
pg_sequencesquery. Our own reading: once an insert has used the value,last_valueis 48211 in the example, and it can be greater when the sequence caches values. Before the first insert after the repair it may read null, because the manual says null means the sequence "has not been read from yet". - The error no longer appears in the PostgreSQL log (the key in the log line is the key to look for).
What to watch afterwards
- After any later bulk load that supplies ids, compare the sequence with
max(id)before the application starts inserting. - Failures that are intermittent and come from selecting the maximum id and adding one are a race, not a lagging sequence. The Serialization Failure Handling page says a unique-key failure of this kind is "effectively a serialization failure" and may be retried, with the caution that "they might represent persistent error conditions". See PostgreSQL "ERROR: could not serialize access due to concurrent update" (40001): retry the whole transaction.
- A restore from a logical dump is scoped by what the dump holds. See A PostgreSQL Dump Restored with Missing Roles or Extensions: Check the Recovery Set.
- pg_dump's page says table data and "sequence values are dumped", but options that skip data (
--schema-only,--exclude-table-data) skip the values too (our reading).
Read next
Related articles you may want next.
- Backup & RecoveryA PostgreSQL Dump Restored with Missing Roles or Extensions: Check the Recovery SetInventory database content, cluster-wide objects and extension packages needed for a usable logical restore.Read article
- TroubleshootingPostgreSQL "ERROR: could not serialize access due to concurrent update" (40001): retry the whole transactionPostgreSQL 'could not serialize access due to concurrent update' (40001)? Read the isolation level, find the overlap, and retry the whole transaction.Read article
- TroubleshootingMongoDB "E11000 duplicate key error collection": find the clashing value, then change the data or the indexMongoDB E11000 duplicate key error collection: read the index and dup key, find the holder with findOne, then fix the data, the _id or the unique index.Read article
Risks and limits
- These commands have not been run or lab-tested.
setvalis immediate and is not transactional, so a rollback does not undo it. Only the saved value undoes it, and a null saved value needs the other undo statement,ALTER SEQUENCE ... RESTART, which is transactional and blocks concurrentnextvalcalls until its transaction ends.- A sequence can have
MAXVALUE,CYCLEor a step other than 1. Thepg_sequencesview listsmax_value,increment_byandcycle; read them before usingmax(id) + 1. - If other systems already hold ids beyond
max(id)(for example a replica that was ahead), choose a higher value than the table suggests. - The message text is a reading of PostgreSQL 17 source; other releases may word it differently.
Sources
- 9.17. Sequence Manipulation Functions — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
- 9.27. System Information Functions and Operators — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
- 52.23. pg_sequences — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
- ALTER SEQUENCE — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
- pg_dump — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
- psql — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
- 29.7. Restrictions — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
- 13.5. Serialization Failure Handling — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
- Appendix A. PostgreSQL Error Codes — PostgreSQL Global Development Group, PostgreSQL 17 documentation, no date shown, accessed 3 December 2026
- nbtinsert.c — PostgreSQL source repository, tag REL_17_9, no date shown, accessed 3 December 2026
- genam.c — PostgreSQL source repository, tag REL_17_9, no date shown, accessed 3 December 2026
This article was originally published on .