Home > Blockchain >  Convert String to Array in postgres
Convert String to Array in postgres

Time:11-24

i Have column to_user in postgres db its type is of varchar it contains UUID. now i want to convert that column into an array of UUID. so i made a new column to_user_copy and copied data from to_user to to_user_copy. i droped the to_user column and created a new column:

ALTER TABLE "transactions" ADD "to_user" character varying array

now i want to convert the UUID's present previouly into array of UUID's.

currently:

@Column("varchar" ,{name:'to_user', array: true })
    toUser: string[];

current column types

current Values

now i want to convert the data present in to_user_copy to array and store it in to_user

          to_user_copy               |         to_user
---------------------------------------------------------------                
dc2544a6-5a5b-4268-9f31-9a9f8bae58aa |           NULL
          to_user_copy                |        to_user
---------------------------------------------------------------                
dc2544a6-5a5b-4268-9f31-9a9f8bae58aa  | {dc2544a6-5a5b-4268-9f31-9a9f8bae58aa}

CodePudding user response:

There is no need to create a new column, to change a column from text to text[]

ALTER TABLE "transactions" 
   alter "to_user" type text[] 
   using array["to_user"];
   

However, UUIDs should be stored in columns defined with the data type uuid.

So this would be the preferred way:

ALTER TABLE "transactions" 
   alter "to_user" type uuid[] 
   using array["to_user"]::uuid[];
  • Related