Split comma separated column data into additional columns

Gallop picture Gallop · Dec 21, 2011 · Viewed 132.2k times · Source

I have comma separated data in a column:

Column 
------- 
a,b,c,d 

I want to split the comma separated data into multiple columns to get this output:

Column1  Column2 Column3 Column4 
-------  ------- ------- -------
a        b       c       d 

How can this be achieved?

Answer

Erwin Brandstetter picture Erwin Brandstetter · Dec 23, 2011

split_part() does what you want in one step:

SELECT split_part(col, ',', 1) AS col1
     , split_part(col, ',', 2) AS col2
     , split_part(col, ',', 3) AS col3
     , split_part(col, ',', 4) AS col4
FROM   tbl;

Add as many lines as you have items in col (the possible maximum). Columns exceeding data items will be empty strings ('').