Skip to content

Instantly share code, notes, and snippets.

@goors
Last active January 29, 2026 20:51
Show Gist options
  • Select an option

  • Save goors/e34c2b5a552c2d0061a8c13d1baa42d7 to your computer and use it in GitHub Desktop.

Select an option

Save goors/e34c2b5a552c2d0061a8c13d1baa42d7 to your computer and use it in GitHub Desktop.
--- PGSQL Script: Bulk Update Schema, Table & Sequence Owners
DO $$
DECLARE
sch RECORD;
obj RECORD;
owner_name TEXT := 'dolphin'; -- <-- declare your owner variable here
BEGIN
-- Loop over all your target schemas
FOR sch IN
SELECT nspname
FROM pg_namespace
WHERE nspname IN ('schema_1', 'schema_2', 'schema_N')
LOOP
-- Change schema owner
EXECUTE format('ALTER SCHEMA %I OWNER TO %I;', sch.nspname, owner_name);
-- Change all tables in this schema
FOR obj IN
SELECT tablename
FROM pg_tables
WHERE schemaname = sch.nspname
LOOP
EXECUTE format('ALTER TABLE %I.%I OWNER TO %I;', sch.nspname, obj.tablename, owner_name);
END LOOP;
-- Change all sequences in this schema
FOR obj IN
SELECT sequence_name
FROM information_schema.sequences
WHERE sequence_schema = sch.nspname
LOOP
EXECUTE format('ALTER SEQUENCE %I.%I OWNER TO %I;', sch.nspname, obj.sequence_name, owner_name);
END LOOP;
END LOOP;
END;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment