SELECT CONCAT_WS(',', Col1, Col2, Col3 ) AS combined FROM table_name
Currently if I have fields Col1 = 'hello', Col2 = 'Bye', Col2 = 'Goodnight'
The above select statement would return hello,Bye,Goodnight which is fine.
What if any of the Cols where blank. A Comma would still be added. like hello,,Goodnight.
Is there a way to say if the Col is empty then ignore it? (This is MySQL)
Function CONCAT_WS
ignores NULL
values and doesn't generate a separator if either of its arguments is NULL
.
For empty, i.e. equal to ''
, values you can use NULLIF
:
SELECT CONCAT_WS(',', NULLIF(Col1, ''), NULLIF(Col2, ''), NULLIF(Col3, '') ) AS combined
FROM table_name