Created
March 31, 2016 12:23
-
Star
(142)
You must be signed in to star a gist -
Fork
(38)
You must be signed in to fork a gist
-
-
Save henriquemenezes/962829815e8e7875f5f4376133b2f209 to your computer and use it in GitHub Desktop.
PostgreSQL set Next ID Sequence Value to MAX(id) from Table
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
-- Get Max ID from table | |
SELECT MAX(id) FROM table; | |
-- Get Next ID from table | |
SELECT nextval('table_id_seq'); | |
-- Set Next ID Value to MAX ID | |
SELECT setval('table_id_seq', (SELECT MAX(id) FROM table)); |
select setval('table_id_seq', max(id)) from table_name; -- Next nextval will return max(id) + 1
If sequence contains uppercase letters in name:
SELECT setval('"Foo"', 42);
Notice the double quotes inside the single quotes
Thank you very much, that was really useful ! Spent hours... lol
See https://wiki.postgresql.org/wiki/Fixing_Sequences to fix all sequences in one go
Not always an issue, but worth noting: the value that it sets it to if there are no rows is 1 which results in the first invocation of nextval
returning 2 and skipping 1.
Thanks !
Thank you!
thanks
The issue persists and can only be resolved by restarting the project after running setval
query
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!!