Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string in characters SQL

Tags:

postgresql

How can I split a string in characters and add a new line after each character in PostgreSQL

For example

num  desc
 1    Hello
 2    Bye

num  desc
 1    H
      e
      l
      l
      o

 2    B
      y 
      e
like image 473
Carlos Escalera Alonso Avatar asked Jun 24 '26 08:06

Carlos Escalera Alonso


1 Answers

select num, regexp_split_to_table(descr,'')
from the_table
order by num;

SQLFiddle: http://sqlfiddle.com/#!15/13c00/4

The order of the characters is however not guaranteed and achieving that is a bit complicated.

Building on Erwin's answer regarding this problem:

select case 
         when row_number() over (partition by id order by rn) = 1 then id 
         else null
       end as id_display, 
       ch_arr[rn]
from (
  select *, 
         generate_subscripts(ch_arr, 1) AS rn
  from (
    select id, 
           regexp_split_to_array(descr,'') as ch_arr
    from data
  ) t1
) t2
order by id, rn;

Edit:

If you just want a single string for each id, where the characters are separated by a newline, you can use this:

select id, 
       array_to_string(regexp_split_to_array(descr,''), chr(10))
from data
order by id

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!