Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select into a 2D array

In PostgreSQL, how can I select some values into a 2D array?

For example, if I want to aggregate a field of data into an array, I would use the ARRAY() constructor or array_agg function e.g.

ARRAY(SELECT s.name FROM myschema.mytable s)

How would I go about selecting say, two values, into a 2D array i.e.

2DARRAYFUNCTION(SELECT s.name, s.id FROM ...)
like image 439
harman_kardon Avatar asked Feb 07 '12 11:02

harman_kardon


1 Answers

If you try to aggregate an ARRAY (build from key and value like in your example) into a two-dimensional array, the aggregate function array_agg() or the ARRAY constructor error out:

I happen to have written an answer for this case exactly recently. Turns out, it's your prequel question.

like image 139
Erwin Brandstetter Avatar answered Oct 06 '22 13:10

Erwin Brandstetter