pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: jdmorgan <jdmorgan@unca.edu>
Cc: pgsql-sql@postgresql.org
Subject: Re: array_agg order by
Date: Mon, 27 Feb 2012 23:15:37 -0500
Message-ID: <25514.1330402537@sss.pgh.pa.us> (raw)
In-Reply-To: <4F4C4EF4.4000006@gmail.com>
References: <4F4C4EF4.4000006@gmail.com>

jdmorgan <jdmorgan@unca.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



view thread (2+ messages)

Message-ID: <25514.1330402537@sss.pgh.pa.us>
Permalink:  ../25514.1330402537@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/25514.1330402537@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: tgl@sss.pgh.pa.us, jdmorgan@unca.edu
  Subject: Re: array_agg order by
  In-Reply-To: <25514.1330402537@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox