Skip to content

Instantly share code, notes, and snippets.

@ekreutz
Last active March 20, 2023 18:23
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Reset SERIAL counter for a PostgreSQL database table

Reset SERIAL counter for a PostgreSQL database table

For the table my_table with a SERIAL column my_id.

SELECT SETVAL(
  pg_get_serial_sequence('my_table', 'my_id'),
  (SELECT COALESCE(MAX(my_id), 0) FROM my_table)
);

This above command sets the counter to the current maximum value of our SERIAL column. Run it to return to normal operations! The addition of COALESCE makes it work even with empty tables; the counter is set to zero.

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