setval Syncs Sequence With max(id)
Bulk imports with explicit ids leave the IDENTITY sequence behind; setval to max(id) via pg_get_serial_sequence makes the next insert safe again.
Code
-- after a bulk import bypasses IDENTITY auto-assignment: the sequence still sits at its old position,
-- so the next ordinary insert would hit the primary key. setval moves the sequence to max(id) in the table
CREATE TEMP TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
label text NOT NULL
);
-- simulate the import: load historical primary keys (GENERATED ALWAYS needs OVERRIDING SYSTEM VALUE)
INSERT INTO invoices (id, label) OVERRIDING SYSTEM VALUE VALUES
(1, 'imported-1'), (2, 'imported-2'), (3, 'imported-3');
-- the sequence's "current value" and the table data are out of sync at this point
SELECT pg_get_serial_sequence('invoices', 'id') AS seq_name;
-- setval(seq, max(id)): with is_called=true semantics, the next nextval returns max+1
SELECT setval(
pg_get_serial_sequence('invoices', 'id'),
(SELECT max(id) FROM invoices)
);
-- ordinary inserts resume: the next one gets 4 automatically, no unique violation
INSERT INTO invoices (label) VALUES ('new-after-import')
RETURNING id;What the code does
Several statements share this file — INSERT / CREATE, with invoices among the objects involved.
invoices is created in this same file as session-local temp tables — nothing needs to exist beforehand, and it goes away at session end.
Breaking the statements into their working parts: a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Using it
The file is self-contained: it creates the session-local tables it uses (invoices), so run it as a whole against a scratch database.
Key statements
SELECT setval(
pg_get_serial_sequence('invoices', 'id'),
(SELECT max(id) FROM invoices)
);
INSERT INTO invoices (id, label) OVERRIDING SYSTEM VALUE VALUES
(1, 'imported-1'), (2, 'imported-2'), (3, 'imported-3');
CREATE TEMP TABLE invoices (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
label text NOT NULL
);
Interactive Tools for This Topic
FAQ
- Which tables does this file reference?
- `invoices` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.