PostgreSQL – How to Change Owner of all Tables in a Schema
To change the owner of all tables within a specific schema in PostgreSQL, you can use a combination of SQL queries to generate and execute the necessary ALTER TABLE
statements.
Run the following SQL query to generate a list of ALTER TABLE
statements for all tables in the schema you want to change the owner of. Replace your_schema_name
with the name of the schema and new_owner_name
with the name of the new owner:
SELECT 'ALTER TABLE ' || table_name || ' OWNER TO new_owner_name;' FROM information_schema.tables WHERE table_schema = 'your_schema_name' AND table_type = 'BASE TABLE';
This query will generate a list of ALTER TABLE
statements for each table in the specified schema.
- Copy the generated
ALTER TABLE
statements from the query result. - Open a new query window in your PostgreSQL client and paste the
ALTER TABLE
statements. - Execute the statements to change the owner of each table to the desired new owner.
Here’s an example of what the ALTER TABLE
statements might look like:
ALTER TABLE your_schema_name.table1 OWNER TO new_owner_name; ALTER TABLE your_schema_name.table2 OWNER TO new_owner_name; -- ... (repeat for each table)
Replace your_schema_name
with the actual schema name, new_owner_name
with the name of the new owner you want to assign to the tables, and repeat the ALTER TABLE
statement for each table in the schema.
Ensure that you have the necessary privileges to execute these statements, as changing table ownership typically requires superuser or other appropriate privileges.