Skip to content

Instantly share code, notes, and snippets.

@lzap
Created May 18, 2022 10:31
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 lzap/a6a9554211d546da52300cc0cd937e60 to your computer and use it in GitHub Desktop.
Save lzap/a6a9554211d546da52300cc0cd937e60 to your computer and use it in GitHub Desktop.
-- Reset all sequences to the maximum value, works on empty tables too
CREATE OR REPLACE FUNCTION reset_sequences()
RETURNS void AS
$reset_sequences$
DECLARE
tn text;
BEGIN
FOR tn IN SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
AND table_name != 'schema_migrations'
LOOP
EXECUTE format(
'SELECT setval(pg_get_serial_sequence(''"%s"'', ''id''), (SELECT COALESCE(MAX("id"), 1) from "%s"))', tn, tn);
END LOOP;
END ;
$reset_sequences$ LANGUAGE 'plpgsql';
@lzap
Copy link
Author

lzap commented May 18, 2022

To call this, just do:

SELECT reset_sequences();

Have fun!

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