I have a table with columns in jsonb
format which contains data like this:
['A', 'B', 'C']
I want to convert column to array column type but I don’t know how to do it properly.
Example of my script structure:
ALTER TABLE "products" ADD COLUMN "test_array" VARCHAR(2)[];
UPDATE "products" SET test_array = do converting here;
ALTER TABLE "products" DROP COLUMN "test";
ALTER TABLE "products" RENAME COLUMN "test_array" TO "test";
3
Answers
The JSONB to ARRAY conversion a bit tricky it can be done by unnest JSONB to rows using
jsonb_array_elements_text
and grouping back usingarray_agg
functions:Try SQL code here
P.S. The conversion works when the table have primary key!
I would suggest a helper function
and then simply
The function may be useful in other cases too.
The syntax looks odd, but this works:
Working fiddle