Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming multiple columns in PostgreSQL

My table has a bunch of columns in the following format:

_settingA
_settingB
_settingB

And I want to rename them simply to add a prefix as follows:

_1_settingA
_1_settingB
_1_settingC

I have a lot more than three columns to rename in this way. If I had just three, I'd just do it manually one by one.

What is the quickest / most efficient way to achieve this?

like image 831
drmrbrewer Avatar asked Oct 28 '15 20:10

drmrbrewer


1 Answers

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.

like image 75
Gabriel's Messanger Avatar answered Sep 24 '22 04:09

Gabriel's Messanger