Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Apeli/cc053604d4b6b5d36a8119c962501011 to your computer and use it in GitHub Desktop.
Save Apeli/cc053604d4b6b5d36a8119c962501011 to your computer and use it in GitHub Desktop.
Reset the pkeys of all tables in a postgres db
DO
$$
DECLARE
tbl regclass;
nbrow bigint;
BEGIN
FOR tbl IN
SELECT c.oid
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname NOT LIKE 'pg\_%' -- system schema(s)
AND c.relname != 'password_resets'. -- table without id column
AND n.nspname <> 'information_schema' -- information schema
ORDER BY n.nspname, c.relname
LOOP
EXECUTE 'SELECT setval(''' || tbl || '_id_seq'', (SELECT MAX(id) FROM ' || tbl || ')+1) ' INTO nbrow;
-- raise notice '%: % rows', tbl, nbrow;
END LOOP;
END
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment