patternsqlModerate
PostgreSQL migrate column to array
Viewed 0 times
postgresqlarraymigratecolumn
Problem
I got a table in PostgreSQL containing a column 'X' of type character (255). Now I would like to migrate that table so that 'X' changes to type character[] (255), but I want the columns original character (255) value to be in the migrated column as an element of the new array in 'X'.
Using sequelize, is there a way to do that through a migration script? Or is there a way to do it in JavaScript with transitions and stuff?
What would be the best (or maybe only) way to go?
Using sequelize, is there a way to do that through a migration script? Or is there a way to do it in JavaScript with transitions and stuff?
What would be the best (or maybe only) way to go?
Solution
The following DDL will convert the column to an array and make the existing value be the first array element:
To reverse this change, you can apply the same logic:
alter table the_table
alter column x type varchar(255)[] using array[x];varchar is a synonym for character varyingTo reverse this change, you can apply the same logic:
alter table the_table
alter column x type varchar(255) using coalesce(x[1],'');x[1] returns the first element, but will only return null if the array is empty. With coalesce() this can then be turned into an empty string ''Code Snippets
alter table the_table
alter column x type varchar(255)[] using array[x];alter table the_table
alter column x type varchar(255) using coalesce(x[1],'');Context
StackExchange Database Administrators Q#204320, answer score: 19
Revisions (0)
No revisions yet.