Skip to content

Instantly share code, notes, and snippets.

@sumanbh
Last active July 14, 2021 22:10
Show Gist options
  • Save sumanbh/d6807bd7d63fdcec7f9fbb5cc227d165 to your computer and use it in GitHub Desktop.
Save sumanbh/d6807bd7d63fdcec7f9fbb5cc227d165 to your computer and use it in GitHub Desktop.
Postgresql PK sequence out of sync (fix)
--Select the max id(or your primary key)--
SELECT MAX(id) FROM *table*;
--See if the next value in the sequence is bigger than the max id--
SELECT nextval('*table*_id_seq');
--If it isn't make it bigger. This fixes "duplicate key violates unique constraint" error--
SELECT setval('*table*_id_seq', (SELECT MAX(id) FROM *table*)+1);
@minaairsupport
Copy link

is there a dynamic way to do it
validate
SELECT CURRVAL(PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id')) AS "Current Value", MAX("Foo_id") AS "Max Value" FROM "Foo";
then correct it
SELECT SETVAL((SELECT PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id')), (SELECT (MAX("Foo_id") + 1) FROM "Foo"), FALSE);
Ref: https://stackoverflow.com/questions/4448340/postgresql-duplicate-key-violates-unique-constraint

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment