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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With