Read Using SQL Snippets before using any of this site's code or techniques on your own systems.

Columns to String

Comma Separated Values (CSV)

To create a string of delimited values from a data set that looks like this

VAL_1  VAL_2  VAL_3  NOTE
------ ------ ------ -------------------------
a                    One NOT NULL, Two NULL
       b             One NOT NULL, Two NULL
              c      One NOT NULL, Two NULL
a      b             Two NOT NULL, One NULL
a      b      c      Three NOT NULL, Zero NULL
                     Zero NOT NULL, Three NULL
 

simply use the concatenation operator, "||", as in the following snippet.

select
  val_1, val_2, val_3,
  val_1 || ',' || val_2 || ',' || val_3 as string
from
  t
order by
  key
;
 
VAL_1  VAL_2  VAL_3  STRING
------ ------ ------ --------------------
a                    a,,
       b             ,b,
              c      ,,c
a      b             a,b,
a      b      c      a,b,c
                     ,,
 

If you need to exclude null values from the end result, try this.

select
  val_1, val_2, val_3,
  ltrim
  ( val_1 ||
      nvl2( val_2, ',' || val_2 , null ) ||
      nvl2( val_3, ',' || val_3 , null ) ,
    ','
  ) as string
from
  t
order by
  key
;
 
VAL_1  VAL_2  VAL_3  STRING
------ ------ ------ --------------------
a                    a
       b             b
              c      c
a      b             a,b
a      b      c      a,b,c
 

Revision Notes

Date Category Note
2007-04-11 Revision Moved topic from old parent topic-11578 to new parent topic-12118.