Last active
July 14, 2021 22:10
-
-
Save sumanbh/d6807bd7d63fdcec7f9fbb5cc227d165 to your computer and use it in GitHub Desktop.
Postgresql PK sequence out of sync (fix)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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