This example tries to demonstrate how regexp_replace can be used to transform CSV text that is stored in a single column in a table into multiple columns in a select statement.
The following select statement creates a column for each value in our CSV data. It uses the regular expression pattern [^,]* which means: any count of non-comma characters.
For the first column, we require that the returned value starts at the beginning of our CSV data, hence the ^ in front of the patter.
The columns 2, 3 and 4 use the occurrence parameter to return the respective value.
select
trim(',' from regexp_substr(csv_line, '^[^,]*' ,1, 1)) col_1,
trim(',' from regexp_substr(csv_line, ',[^,]*' ,1, 1)) col_2,
trim(',' from regexp_substr(csv_line, ',[^,]*' ,1, 2)) col_3,
trim(',' from regexp_substr(csv_line, ',[^,]*' ,1, 3)) col_4
from
tq84_csv_data;
--
-- COL_1 COL_2 COL_3 COL_4
-- ---------- ---------- ---------- ----------
-- one two three four
-- foo bar baz qux
-- 1 3
-- i ii iii iv
-- ** *** ****