HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMajor

PostgreSQL Change owner of all tables under a specific schema

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
postgresqlownertablesallunderspecificchangeschema

Problem

I am trying to change the owner of all tables under the same schema in one command line. i.e: alter table schema_name.* owner to newowner. Is there a way to accomplish that?

Solution

Reassigned Owned

There is a specific privilege command that does just this, RESASSIGN OWNED. This reassigns all objects, not just ones in a specific schema.

Schema-specific

You can generate the ALTER TABLE commands with the following,

SELECT format(
  'ALTER TABLE %I.%I.%I OWNER TO %I;',
  table_catalog,
  table_schema,
  table_name,
  current_user  -- or another just put it in quotes
)
FROM information_schema.tables
WHERE table_schema = 'mySchema';


In psql, you can run them by following it immediately with \gexec

Code Snippets

SELECT format(
  'ALTER TABLE %I.%I.%I OWNER TO %I;',
  table_catalog,
  table_schema,
  table_name,
  current_user  -- or another just put it in quotes
)
FROM information_schema.tables
WHERE table_schema = 'mySchema';

Context

StackExchange Database Administrators Q#52195, answer score: 49

Revisions (0)

No revisions yet.