Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

Dev-Dipesh commented Apr 7, 2018

Last one should be:

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

This comment has been minimized.

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

This comment has been minimized.

Copy link

ikunyemingor commented Sep 12, 2018

@Dev-Dipesh it worked... thanks

@Yossit-sweetinn

This comment has been minimized.

Copy link

Yossit-sweetinn commented Jul 24, 2019

@Dev-Dipesh thanks.

@vedtam

This comment has been minimized.

Copy link

vedtam commented Aug 20, 2019

Thanks!

@6high

This comment has been minimized.

Copy link

6high commented Nov 6, 2019

thanks

@fabioespinosa

This comment has been minimized.

Copy link

fabioespinosa commented Dec 5, 2019

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

Notice the double quotes inside the single quotes

@olistik

This comment has been minimized.

Copy link

olistik commented Dec 14, 2019

Thanks!

@RedShift1

This comment has been minimized.

Copy link

RedShift1 commented Jan 12, 2020

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.