Renaming multiple columns in PostgreSQL

淺唱寂寞╮ 提交于 2019-12-05 09:01:39
Gabriel's Messanger

There's no single command aproach. Obviously you could type multiple comands for RENAME by your self, but let me intoduce some improvement:) As I said in this answer

...for all such bulk-admin-operations you could use PostgreSQL system tables to generate queries for you instead of writing them by hand

In your case it would be:

SELECT
    'ALTER TABLE ' || tab_name || ' RENAME COLUMN '
    || quote_ident(column_name) || ' TO '
    || quote_ident( '_1' || column_name) || ';'
FROM (
    SELECT
        quote_ident(table_schema) || '.' || quote_ident(table_name) as tab_name,
        column_name
    FROM information_schema.columns  
    WHERE 
            table_schema = 'schema_name'
            AND table_name = 'table_name'
            AND column_name LIKE '\_%'
) sub;

That'll give you set of strings which are SQL commands like:

ALTER TABLE  schema_name.table_name RENAME COLUMN "_settingA" TO "_1_settingA";
ALTER TABLE  schema_name.table_name RENAME COLUMN "_settingB" TO "_1_settingB";
...

There no need using table_schema in WHERE clause if your table is in public schema. Also remember using function quote_ident() -- read my original answer for more explanation.

Edit:

I've change my query so now it works for all columns with name begining with underscore _. Because underscore is special character in SQL pattern matching, we must escape it (using \) to acctually find it.

Something simple like this will work.

SELECT FORMAT(
  'ALTER TABLE %I.%I.%I RENAME %I TO %I;',
  table_catalog,
  table_schema,
  table_name,
  column_name,
  '_PREFIX_' + column_name
)
FROM information_schema.columns
WHERE table_name = 'foo';

%I will do quote_ident, which is substantially nicer. If you're in PSQL you can run it with \gexec

You can't do that.

All the actions except RENAME and SET SCHEMA can be combined into a list of multiple alterations to apply in parallel.

most efficient way is using ActiveRecord.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!