Sub topic 13
Fixing the sequence after loading data
This chapter assumes you can create identity columns, you know the difference between GENERATED ALWAYS and GENERATED BY DEFAULT, and you have seen OVERRIDING SYSTEM VALUE in the previous chapters. It also assumes you know that an identity column is backed by a sequence.
Why the sequence falls out of step
The identity sequence and the table are separate objects. The sequence only advances when something calls nextval on it, which happens when an insert uses the generated default. If a row arrives with an explicit ID, PostgreSQL stores it and does not look at the sequence.
These paths put explicit IDs into an identity column without moving the sequence:
INSERT ... OVERRIDING SYSTEM VALUEinto aGENERATED ALWAYScolumn.- Plain
INSERTwith an explicitidinto aGENERATED BY DEFAULTcolumn. COPY ... FROM, which accepts explicit values for identity columns, includingALWAYSones. This is howpg_dumpdata restores work.- Rows copied from another database or restored from a CSV export.
The table now contains IDs the sequence has never handed out. The sequence will eventually reach those IDs and collide with them.
Reproducing the problem
This script runs as shown on a fresh database.
CREATE TABLE products (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL
);
INSERT INTO products (id, name)
OVERRIDING SYSTEM VALUE
VALUES (1, 'Pen'), (2, 'Ink'), (3, 'Paper');
INSERT INTO products (name) VALUES ('Stapler');
-- ERROR: duplicate key value violates unique constraint "products_pkey"
-- DETAIL: Key (id)=(1) already exists.The first load worked. The next ordinary insert failed because the sequence still started at 1.
The failed insert also consumed the value 1. If you retry, you get 2, then 3, and only the fourth attempt succeeds. Each failure burns a sequence value, so retrying without fixing the sequence leaves gaps.
Checking whether a sequence is behind
Compare the table maximum with the sequence position. The pg_sequences view shows the last value handed out, or NULL if the sequence has never been used.
SELECT max(id) AS table_max FROM products;
SELECT last_value
FROM pg_sequences
WHERE schemaname = 'public' AND sequencename = 'products_id_seq';If last_value is NULL or lower than table_max, the sequence is behind. The sequence name products_id_seq is the default name for an identity column. To avoid guessing, use pg_get_serial_sequence, shown next.
Resynchronizing with setval
setval(sequence, value, is_called) sets the sequence position. pg_get_serial_sequence(table, column) finds the sequence behind an identity column, so you do not hard-code its name.
SELECT setval(
pg_get_serial_sequence('products', 'id'),
coalesce(max(id), 0) + 1,
false
)
FROM products;
INSERT INTO products (name) VALUES ('Stapler') RETURNING id;The query returns 4 for setval, and the insert returns id = 4.
The third argument decides what happens next:
falsemeans the value has not been handed out yet.nextvalreturns exactly the value you set. This form is safe on an empty table:coalesce(max(id), 0) + 1gives 1, and the first ID is 1.truemeans the value counts as already used, sonextvalreturns the value plus the increment. This is the default when you omit the third argument.
The shorter form from the earlier chapter, setval(seq, max(id)), is equivalent to setval(seq, max(id), true). It works on any table with rows. On an empty table max(id) is NULL, and setval does nothing when its argument is NULL, so the sequence stays where it was. That is usually fine, but the false form states the intent more clearly.
Increments other than 1
If the identity was created with INCREMENT BY 10, setval(seq, max(id), true) makes the next ID max + 10. The false form with max + 1 hands out max + 1 first and then continues in steps of 10. Pick the form that matches the ID pattern you want.
Alternative: ALTER ... RESTART WITH
You can also restart the sequence through the table.
DO $$
DECLARE
next_id bigint;
BEGIN
SELECT coalesce(max(id), 0) + 1 INTO next_id FROM products;
EXECUTE format('ALTER TABLE products ALTER COLUMN id RESTART WITH %s', next_id);
END $$;RESTART WITH only accepts a literal number, not a subquery. That is why this version needs a DO block and dynamic SQL.
| Approach | Accepts a subquery | Takes a lock on the sequence | Undone by a rollback |
|---|---|---|---|
| `setval(...)` | Yes | No | No |
| `ALTER ... RESTART WITH` | No, needs `EXECUTE` | Yes | Yes |
For one-off repairs setval is simpler. Choose ALTER ... RESTART WITH when you want the repair to be part of a migration that can roll back as a whole.
Concurrency and other edge cases
The query max(id) and the setval call are two steps. If another session inserts with the generated default between them, your setval can move the sequence backward and cause the same duplicate errors later. Two ways to avoid this:
- Run the fix during a quiet period, right after the load finishes and before the application writes again.
- Block writers while you fix it. A table lock in
EXCLUSIVEmode stops other inserts but still allows reads.
BEGIN;
LOCK TABLE products IN EXCLUSIVE MODE;
SELECT setval(
pg_get_serial_sequence('products', 'id'),
coalesce(max(id), 0) + 1,
false
)
FROM products;
COMMIT;Other cases to watch for:
- Sequence cache. If the sequence was created with
CACHEgreater than 1, other sessions may hold preallocated values. After yoursetval, those sessions can still hand out older, lower numbers. With the defaultCACHE 1this does not happen. - Limits.
setvalraises an error if the value is outside the sequence's minimum and maximum. Loading IDs close to the maximum of anintegercolumn is a sign you should move tobigint. - Gaps are fine. After a resync you may skip numbers. That does not matter. Identity values were never a gapless counter.
- Replicas and restores. Physical replicas copy sequence state. Logical replication has historically copied rows without sequence positions, so check your version's behavior and resync the new primary before it takes writes. A
pg_dumprestore emits its ownsetvalcalls, so a dump restored in full is already in sync. - Partial loads. If you load only some rows, for example a subset of an archive, the sequence must be above the highest ID in the whole table, not just the loaded batch.
A checklist for bulk loads
- Load the data, using
COPYorOVERRIDING SYSTEM VALUE. - Lock out writers if the application is live.
- Run
setval(pg_get_serial_sequence(...), coalesce(max(id), 0) + 1, false). - Test with one ordinary
INSERT ... RETURNING idand confirm the ID is greater than the table maximum. - Release the lock.
Practice
Exercise
A table invoices has a GENERATED BY DEFAULT AS IDENTITY column id. A migration script loaded 500 rows with explicit IDs from 1 to 500 using COPY, and the next normal insert fails with a duplicate key error on invoices_pkey. Write the statement that fixes it so the next generated ID is 501, and explain why the failed insert makes the problem worse if you simply retry.
Show answer
SELECT setval(pggetserial_sequence('invoices', 'id'), coalesce(max(id), 0) + 1, false) FROM invoices; This sets the sequence to 501 without marking it as used, so the next nextval returns 501. Each failed insert still calls nextval before the duplicate is detected, so every retry consumes one sequence value (1, then 2, and so on) and leaves a gap. The sequence only reaches 501 after 500 failed retries.
Exercise
Why does setval(seq, max(id)) do nothing on an empty table, and which form avoids relying on that behavior?
Show answer
On an empty table max(id) is NULL, and setval returns NULL without changing the sequence when given a NULL argument. The sequence keeps its starting position, so the first insert still gets the start value. The form setval(seq, coalesce(max(id), 0) + 1, false) avoids relying on this, because it explicitly sets the next value to 1 on an empty table.