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?
split_part()
does what you want in one step:Add as many lines as you have items in
col
(the possible maximum). Columns exceeding data items will be empty strings (''
).If the number of fields in the CSV is constant then you could do something like this:
For example:
If the number of fields in the CSV is not constant then you could get the maximum number of fields with something like this:
and then build the appropriate
a[1], a[2], ..., a[M]
column list for your query. So if the above gave you a max of 6, you'd use this:You could combine those two queries into a function if you wanted.
For example, give this data (that's a NULL in the last row):
Since your delimiter is a simple fixed string, you could also use
string_to_array
instead ofregexp_split_to_array
:Thanks to Michael for the reminder about this function.
You really should redesign your database schema to avoid the CSV column if at all possible. You should be using an array column or a separate table instead.
You can use split function.