Search code examples
postgresqlhstore

Merge existing columns in POstgreSQL 9.1 hstore column


I have a PostgreSQL 9.1 database table (let's call it MyTable) looking like this:

 gid | name | address | phone | colA | colB | colC | colD
------------------------------------------------------------
     |      |         |       |      |       |      |   

I enabled in this database hstore:

 CREATE EXTENSION hstore;

Now, I want to create a hstore column (colH), where to store the columns colA colB colC colD, with key their name and values, their values.

ALTER TABLE MyTable ADD COLUMN colH hstore;

Now, how I insert the values in the hstore column? I think INSERT would help but I do not know how to do it. Please help.


Solution

  • Insert is used to create new rows, not to change columns of existing rows.

    You need to use update after adding the hstore column:

    update mytable
       set colh = hstore('cola', cola)||hstore('colb', colb)||hstore('colc', colc)||hstore('cold', cold);
    

    or - slightly more compact:

    update mytable
        set colh = hstore(array['cola','colb','colc','cold'], array[cola,colb,colc,cold]);
    

    This assumes that cola, colb, colc and cold are of type text or varchar. If they are not you need to cast them properly.

    After that you can drop the columns you don't need any longer.