This is my People table, and I'm looking to get one array for each column as output.
| name | surname |
|---|---|
| Cell 1 | Cell 4 |
| Cell 2 | Cell 5 |
| Cell 3 | Null |
SELECT array_agg(name) AS names FROM people
I only understand how to return one array from the table, but I would like to have one array for each column without any expression (comparing).
Im looking for a Result like this below:
((Cell1, Cell2, Cell3), (Cell4, Cell5))
It would be also fine to use different Tables instead of Columns. So turning two Queries below, into one
SELECT array_agg(name) FROM name
SELECT array_agg(surname) FROM surname
First of all :
((Cell1, Cell2, Cell3), (Cell4, Cell5))is not the right notation for a sql array.{{Cell1, Cell2, Cell3}, {Cell4, Cell5}}is the right notation for a text array but you will get the sql error "Multidimensional arrays must have sub-arrays with matching dimensions" because the first sub-array is of dimension 3 whereas the second sub-array is of dimension 2, which is not accepted for sql arrays.So you have two solutions here :
Solution 1 : including NULL values so that both sub-arrays have the same dimension :
The result is of type
text[]:Solution 2 : replacing the sql array by a
jsonarray which accepts sub-arrays with various dimensions while excluding theNULLvalues for thesurnamecolumn :The result is of type
json:Last but not least, when name and surname come from two different tables :
or