Skip to content

Instantly share code, notes, and snippets.

@henriquemenezes
Created March 31, 2016 12:23
Show Gist options
  • Save henriquemenezes/962829815e8e7875f5f4376133b2f209 to your computer and use it in GitHub Desktop.
Save henriquemenezes/962829815e8e7875f5f4376133b2f209 to your computer and use it in GitHub Desktop.
PostgreSQL set Next ID Sequence Value to MAX(id) from Table
-- 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));
@Dev-Dipesh
Copy link

Last one should be:

SELECT setval('table_id_seq', (SELECT MAX(id) FROM table)+1);

@quantizer
Copy link

quantizer commented Jun 14, 2018

@Dev-Dipesh due to docs we don't need +1.

SELECT setval('foo', 42);           Next nextval will return 43
SELECT setval('foo', 42, true);     Same as above
SELECT setval('foo', 42, false);    Next nextval will return 42

@ikunyemingor
Copy link

@Dev-Dipesh it worked... thanks

@Yossit-sweetinn
Copy link

@Dev-Dipesh thanks.

@vedtam
Copy link

vedtam commented Aug 20, 2019

Thanks!

@6high
Copy link

6high commented Nov 6, 2019

thanks

@fabioespinosa
Copy link

If sequence contains uppercase letters in name:
SELECT setval('"Foo"', 42);

Notice the double quotes inside the single quotes

@olistik
Copy link

olistik commented Dec 14, 2019

Thanks!

@RedShift1
Copy link

See https://wiki.postgresql.org/wiki/Fixing_Sequences to fix all sequences in one go

@prempopatia
Copy link

See https://wiki.postgresql.org/wiki/Fixing_Sequences to fix all sequences in one go

Thanks for this.

@urpylka
Copy link

urpylka commented Jan 1, 2021

Hello, it didn't fit me (if the table is empty, if I need to reset to the first value). I've made my own procedure based on it, maybe it can be helpful for somebody. https://urpylka.com/posts/post-15/

@denis-petrov
Copy link

Thanks!

@ahsan-babar
Copy link

Thank you

@mbustamanteo
Copy link

See https://wiki.postgresql.org/wiki/Fixing_Sequences to fix all sequences in one go

Thank you!!

@zouchao
Copy link

zouchao commented Apr 8, 2022

select setval('table_id_seq', max(id)) from table_name;  -- Next nextval will return  max(id) + 1

Copy link

ghost commented May 19, 2022

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

@liaden
Copy link

liaden commented Jun 9, 2022

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.

@mjerem34
Copy link

Thanks !

@joedave13
Copy link

Thank you!

@naimurhasan
Copy link

thanks

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