-
-
Save lzap/a6a9554211d546da52300cc0cd937e60 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To call this, just do:
SELECT reset_sequences();
Have fun!