Created
October 6, 2019 19:59
-
-
Save qweeze/4e6c6d1e07266d521efe1fa0021f10a2 to your computer and use it in GitHub Desktop.
Reset all sequences in a postgresql database
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 MAX(column) value | |
DO | |
$$ | |
DECLARE | |
rec RECORD; | |
idd integer; | |
BEGIN | |
FOR rec IN | |
SELECT S.relname AS seqname, C.attname AS colname, T.relname AS tblname | |
FROM pg_class AS S, pg_depend AS D, pg_class AS T, pg_attribute AS C | |
WHERE S.relkind = 'S' | |
AND S.oid = D.objid | |
AND D.refobjid = T.oid | |
AND D.refobjid = C.attrelid | |
AND D.refobjsubid = C.attnum | |
ORDER BY S.relname | |
LOOP | |
RAISE notice 'Resetting %', rec.seqname; | |
EXECUTE | |
'SELECT SETVAL( | |
' ||quote_literal(rec.seqname)|| ', MAX(' ||quote_ident(rec.colname)|| ') | |
) FROM ' ||quote_ident(rec.tblname)|| ';'; | |
END LOOP; | |
END | |
$$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment