Search code examples
sqlpostgresqlsql-function

How convert string to array on SQL


In a column I have "1;2;3;6-9"

I need make this string in a array like this (1,2,3,6,7,8,9)

select range from my_table

return

| range     |
|-----------| 
| 1;2;3;6-9 |

I need run

select id from my_another_table where id in("1;2;3;6-9")
| id |
|----| 
| 1  |
| 2  |
| 3  |
| 6  |
| 7  |
| 8  |
| 9  |

Solution

  • This is a lousy structure for data. But you can do this with generate_series() and string functions:

    select generate_series(v2.lo, v2.hi, 1)
    from (values ('1;2;3;6-9')) v(str) cross join lateral
         regexp_split_to_table(v.str, ';') as r(range) cross join lateral
         (values (case when range not like '%-%' then range::int else split_part(range, '-', 1)::int end,
                  case when range not like '%-%' then range::int else split_part(range, '-', 2)::int end
                 )
         ) v2(lo, hi);