0

Need some help splitting column data (string) in Postgres into multiple dummy columns such as:

---------column-------
data1;data2;data3 -
data1;data3       -
data1             -

into

- Col1 ---- Col2 ---- Col3
   1    |    1    |   1
   1    |    0    |   1
   1    |    0    |   0

I know the maximum number of columns so I can preset the dummy columns. Do I need to do some sort of for loop?

JP

1 Answer 1

3

You can either use split_part():

select split_part(col, ';', 1) as col1, 
       split_part(col, ';', 2) as col2, 
       split_part(col, ';', 3) as col1
from the_table;

Or slightly more efficient because the splitting is only done once per row:

select c[1] as col1, 
       c[2] as col2, 
       c[3] as col3
from (
  select string_to_array(col, ';') as c
  from the_table
) t;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.