3

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
Carlos Escalera Alonso
  • 2,303
  • 1
  • 23
  • 36

1 Answers1

3
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
Community
  • 1
  • 1
a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843