Re: array_agg order by

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: jdmorgan <jdmorgan(at)unca(dot)edu>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: array_agg order by
Date: 2012-02-28 04:15:37
Message-ID: 25514.1330402537@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

jdmorgan <jdmorgan(at)unca(dot)edu> writes:
> I am using a array_agg to get a subset of data to use in a
> query.However, I can't figure out how to get the data returned in the
> array_agg function to sort with an order by function.Any help would be
> appreciated.Here is my query as it is now.I am using postgresql 8:

Well, if you were using 9.0 or later, you could do this "right":

select array_agg(foo order by bar), otherstuff from ..tables..;

You can kind of get there in older versions with a sub-select:

select array_agg(foo), otherstuff
from
(select foo, otherstuff from ..tables.. order by whatever) ss;

However that's a bit shaky because you can't do very much in the outer
query, like say grouping, without risking messing up the sort ordering.
You have to keep a close eye on the EXPLAIN output for your query to
make sure nothing re-sorts the data before it gets to the Aggregate
step.

regards, tom lane

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Rehan Saleem 2012-02-28 08:50:04 How to convert SQL store procedure to Postgresql function
Previous Message jdmorgan 2012-02-28 03:50:12 array_agg order by