1

How can I put an sql query result in a string array with Postgres? I have some attributes in the column 'zone' of the table 'mytable' and I must put them all in a String[] areas; This is my first request, sorry if I made some format mistake.

  • 2
    You forgot to provide the data type of the column and your version of Postgres. String[] is not a valid Postgres type. I suppose you mean text[]? And do you want to aggregate all attributes from all rows into one array or just attributes from one row? – Erwin Brandstetter May 7 '15 at 0:00
  • yes, i use postgres 9.4 and the String[] areas is the array where i will put the text attributes. I want to aggregate all attributes of a column – Filippo Vimini May 8 '15 at 15:39
3

You can use an array constructor:

select array(
select zone
from mytable) 
as areas;
  • 2
    I feel array_agg() is a bit more convenient, no need to use a subquery, for example. – dezso May 7 '15 at 10:25
  • 1
    @dezso: The array constructor (which is not an "operator"!) is typically faster to build a single array. So this is actually the best technique. – Erwin Brandstetter May 11 '15 at 3:31
  • I've just made a small test where I see the two producing the exact same query plan, therefore the same execution time. – dezso May 11 '15 at 13:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.