Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename all columns from all tables with specific column name in PostgreSQL?

Is there a way I can rename all column names that are called 'location' to 'location_name' within all schemas in my PostgreSQL database?

I am fairly new to SQL and am aware there is an ALTER TABLE command but don't know if it is possible to somehow loop through all tables?

like image 796
Chris Avatar asked Aug 23 '16 07:08

Chris


People also ask

How do I rename multiple columns in PostgreSQL?

First, specify the table, which contains the column you want to rename, after the ALTER TABLE clause. Second, provide the column name after the RENAME COLUMN clause. Third, give the new column name after the TO keyword.

How do I rename a table column in PostgreSQL?

Syntax. The syntax to rename a column in a table in PostgreSQL (using the ALTER TABLE statement) is: ALTER TABLE table_name RENAME COLUMN old_name TO new_name; table_name.


Video Answer


1 Answers

You need dynamic SQL for this using an anonymous PL/pgSQL block to do this in an automated way:

do
$$
declare
  l_rec record;
begin
  for l_rec in (select table_schema, table_name, column_name 
                from information_schema.columns 
                where table_schema = 'public' 
                  and column_name = 'location') loop
     execute format ('alter table %I.%I rename column %I to %I_name', l_rec.table_schema, l_rec.table_name, l_rec.column_name, l_rec.column_name);
  end loop;
end;
$$

If you have multiple schemas or your tables are not in the public schema, replace the condition where table_schema = 'public' with the appropriate restriction.

like image 155
a_horse_with_no_name Avatar answered Sep 29 '22 17:09

a_horse_with_no_name