0

Say you have a table:

CREATE TABLE tab (
x  integer,
y  integer,
); 

And multiple rows of the form x, [y1, y2, ...]:

x ys
1 [2,3]
4 [5,6,7]

There might be an arbitrary but non-zero (or non-nil) amount of ys in each row. x always non-nil.

How to insert such that you end up with a row for each x, y pair, that is:

x y
1 2
1 3
4 5
4 6
4 7
2
  • Where do the arrays come from? Commented May 20, 2020 at 11:35
  • @a_horse_with_no_name by manual specification in the SQL statement Commented May 20, 2020 at 11:36

1 Answer 1

3

You can unnest() the arrays:

insert into tab (x,y)
select v.x, t.y
from (
 values 
   (1, array[2,3]), 
   (4, array[5,6,7])
) as v(x,ya) 
  cross join unnest(v.ya) as t(y)

Online example

Sign up to request clarification or add additional context in comments.

Comments

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.