I have two array values of the same length in PostgreSQL:
{a,b,c} and {d,e,f}
and I’d like to combine them into
{{a,d},{b,e},{c,f}}
Is there a way to do that?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Postgres 9.5 or later
has
array_agg(array expression):This is a drop-in replacement for my custom aggregate function
array_agg_mult()demonstrated below. It’s implemented in C and considerably faster. Use it.Postgres 9.4
Use the
ROWS FROMconstruct or the updatedunnest()which takes multiple arrays to unnest in parallel. Each can have a different length. You get (per documentation):Use this cleaner and simpler variant:
Postgres 9.3 or older
Simple zip()
Consider the following demo for Postgres 9.3 or earlier:
Result:
Note that both arrays must have the same number of elements to unnest in parallel, or you get a cross join instead.
You can wrap this into a function, if you want to:
Call:
Same result.
zip() to multi-dimensional array:
Now, if you want to aggregate that new set of arrays into one 2-dimenstional array, it gets more complicated.
or:
or:
will all result in the same error message (tested with pg 9.1.5):
But there is a way around this, as we worked out under this closely related question.
Create a custom aggregate function:
And use it like this:
Result:
Note the additional
ARRAY[]layer! Without it and just:You get:
Which may be useful for other purposes.
Roll another function:
Call:
Result: