Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql split column into rows

Tags:

postgresql

I have 2 columns with a list of towns and I want to split the towns into rows

user 1 | [town1,town2,town3]

I want to split this into rows:

user 1 | town 1
user 1 | town 2
user 1 | town 3
like image 935
user1609817 Avatar asked Oct 15 '25 15:10

user1609817


2 Answers

Try this:

SELECT 
    username, 
    regexp_split_to_table(towns, E',') 
FROM yourTable

SQLFIDDLE DEMO

like image 55
Rahul Tripathi Avatar answered Oct 18 '25 06:10

Rahul Tripathi


Assuming the columns are named user_name and towns you can do something like this:

select t1.user_name, t2.town
from the_table t1
  cross join lateral unnest(string_to_array(t1.towns,',')) as t2 (town)

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!