Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL (Maria DB) split string separated by comma to rows

I have this column:

names
John, Mary
Joseph
Eleanor, Sophia, Dani

And I want this output:

names
John
Mary
Joseph
Eleanor
Sophia
Dani

And it should include the SUBSTRING_INDEX function

like image 912
Ana Avatar asked May 20 '26 00:05

Ana


1 Answers

You can use a recursive CTE:

with recursive cte as (
      select '            ' as name, concat(names, ',') as names, 1 as lev
      from t
      union all
      select substring_index(names, ',', 1),
             substr(names, instr(names, ',') + 2), lev + 1
      from cte
      where names like '%,%'
     )
select name
from cte
where lev > 1;

Here is a db<>fiddle.

like image 141
Gordon Linoff Avatar answered May 22 '26 13:05

Gordon Linoff