Skip to content

Instantly share code, notes, and snippets.

@qweeze
Created October 6, 2019 19:59
Show Gist options
  • Save qweeze/4e6c6d1e07266d521efe1fa0021f10a2 to your computer and use it in GitHub Desktop.
Save qweeze/4e6c6d1e07266d521efe1fa0021f10a2 to your computer and use it in GitHub Desktop.
Reset all sequences in a postgresql database
-- 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