Skip to content

Instantly share code, notes, and snippets.

@wdhowe
Created October 24, 2024 13:36
Show Gist options
  • Save wdhowe/c522a4fc057b6f0373a932cfb40525ec to your computer and use it in GitHub Desktop.
Save wdhowe/c522a4fc057b6f0373a932cfb40525ec to your computer and use it in GitHub Desktop.
Postgresql: Update all Sequences to Latest
DO $$
DECLARE
i TEXT;
BEGIN
FOR i IN (
SELECT 'SELECT SETVAL('
|| quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname))
|| ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM '
|| quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
FROM pg_class AS S,
pg_depend AS D,
pg_class AS T,
pg_attribute AS C,
pg_tables AS PGT
WHERE S.relkind = 'S'
AND S.oid = D.objid
AND D.refobjid = T.oid
AND D.refobjid = C.attrelid
AND D.refobjsubid = C.attnum
AND T.relname = PGT.tablename
) LOOP
EXECUTE i;
END LOOP;
END $$;
CREATE OR REPLACE FUNCTION update_seqs_to_latest()
RETURNS void
LANGUAGE plpgsql
VOLATILE
AS $$
DECLARE
i TEXT;
BEGIN
FOR i IN (
SELECT 'SELECT SETVAL('
|| quote_literal(quote_ident(PGT.schemaname) || '.' || quote_ident(S.relname))
|| ', COALESCE(MAX(' ||quote_ident(C.attname)|| '), 1) ) FROM '
|| quote_ident(PGT.schemaname)|| '.'||quote_ident(T.relname)|| ';'
FROM pg_class AS S,
pg_depend AS D,
pg_class AS T,
pg_attribute AS C,
pg_tables AS PGT
WHERE S.relkind = 'S'
AND S.oid = D.objid
AND D.refobjid = T.oid
AND D.refobjid = C.attrelid
AND D.refobjsubid = C.attnum
AND T.relname = PGT.tablename
) LOOP
EXECUTE i;
RAISE NOTICE 'Executed: %', i;
END LOOP;
RAISE NOTICE 'All sequences updated successfully';
END;
$$;
-- To use the function, simply call:
-- SELECT update_seqs_to_latest();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment