Skip to content

Instantly share code, notes, and snippets.

@ekreutz
Last active March 20, 2023 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekreutz/7cf3f383ecf71d3b1c3eeb30b5fb3882 to your computer and use it in GitHub Desktop.
Save ekreutz/7cf3f383ecf71d3b1c3eeb30b5fb3882 to your computer and use it in GitHub Desktop.
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