Received: from magus.postgresql.org (magus.postgresql.org [87.238.57.229]) by mail.postgresql.org (Postfix) with ESMTP id A81BB9552CF for ; Tue, 28 Feb 2012 00:15:56 -0400 (AST) Received: from sss.pgh.pa.us ([66.207.139.130]) by magus.postgresql.org with esmtp (Exim 4.72) (envelope-from ) id 1S2ETe-0001S9-Ny for pgsql-sql@postgresql.org; Tue, 28 Feb 2012 04:15:55 +0000 Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id q1S4Fbvh025515; Mon, 27 Feb 2012 23:15:37 -0500 (EST) To: jdmorgan cc: pgsql-sql@postgresql.org Subject: Re: array_agg order by In-reply-to: <4F4C4EF4.4000006@gmail.com> References: <4F4C4EF4.4000006@gmail.com> Comments: In-reply-to jdmorgan message dated "Mon, 27 Feb 2012 22:50:12 -0500" Date: Mon, 27 Feb 2012 23:15:37 -0500 Message-ID: <25514.1330402537@sss.pgh.pa.us> From: Tom Lane X-Pg-Spam-Score: -1.9 (-) X-Archive-Number: 201202/88 X-Sequence-Number: 36381 jdmorgan 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