0

I have a table in Postgresql. one of the fields have multiple string, I want to put this string in different rows. I used:

id  lng  lat  descriptions
1   0.98 51   walk, wedding, bus

and insert into another table like this:

id  lng   lat  descriptions
1   0.98   51   walk
1   0.98   51   wedding
1   0.98   51   bus

1 Answer 1

1

Use unnest() with regexp_split_to_array():

WITH tb(id,lng,lat,descriptions) AS ( VALUES
  (1,0.98,51,'walk, wedding, bus')
)
SELECT id,lng,lat,trim(unnest(regexp_split_to_array(descriptions,','))) AS descriptions FROM tb;

Result:

 id | lng  | lat | descriptions 
----+------+-----+--------------
  1 | 0.98 |  51 | walk
  1 | 0.98 |  51 | wedding
  1 | 0.98 |  51 | bus
(3 rows)
Sign up to request clarification or add additional context in comments.

1 Comment

If you are using regex then regexp_split_to_table() should be faster then a combination of unnest() and regexp_split_to_array(). But using a regex is not needed here and string_to_array() will be a faster than regexp_split_to_array()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.