X-Original-To: pgsql-sql-postgresql.org@postgresql.org Received: from localhost (wm.hub.org [200.46.204.128]) by postgresql.org (Postfix) with ESMTP id BEBD89F9F7C for ; Tue, 12 Sep 2006 17:45:26 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.128]) (amavisd-new, port 10024) with ESMTP id 97666-03-3 for ; Tue, 12 Sep 2006 20:42:33 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey- Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by postgresql.org (Postfix) with ESMTP id 17DCC9FB2B5 for ; Tue, 12 Sep 2006 17:38:12 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.13.6/8.13.6) with ESMTP id k8CKbtAw021366; Tue, 12 Sep 2006 16:37:56 -0400 (EDT) To: Michael Fuhr cc: Steven Murdoch , pgsql-sql@postgresql.org Subject: Re: Sorting items in aggregate function In-reply-to: <20060912181759.GA66966@winnie.fuhr.org> References: <20060912154628.GB4991@cl.cam.ac.uk> <20060912181759.GA66966@winnie.fuhr.org> Comments: In-reply-to Michael Fuhr message dated "Tue, 12 Sep 2006 12:17:59 -0600" Date: Tue, 12 Sep 2006 16:37:55 -0400 Message-ID: <21365.1158093475@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200609/87 X-Sequence-Number: 26298 Michael Fuhr writes: > On Tue, Sep 12, 2006 at 04:46:28PM +0100, Steven Murdoch wrote: >> Here is an example of a setup and what I could like to achieve. Does >> anyone have suggestions on what is the best way to get the desired >> result? > Use the aggregate over an ordered subquery: > SELECT name, trim(concat(code || ' ')) AS codes > FROM ( > SELECT a.name, b.code > FROM a > LEFT JOIN ab ON a.id = ab.a_id > LEFT JOIN b ON ab.b_id = b.id > ORDER BY b.code > ) AS s > GROUP BY name > ORDER BY name; Note that if you need to GROUP in the outer query, it's best to sort the inner query's output first by the outer query's grouping: SELECT name, trim(concat(code || ' ')) AS codes FROM ( SELECT a.name, b.code FROM a LEFT JOIN ab ON a.id = ab.a_id LEFT JOIN b ON ab.b_id = b.id ORDER BY a.name, b.code ^^^^^^^^^^^^^^ ) AS s GROUP BY name ORDER BY name; This way will still work if the planner decides to use a GroupAggregate (which in fact it probably will, if it sees it can avoid another sort step). The way Michael showed will only work if the plan uses HashAggregate --- if the planner decides it needs Sort+GroupAggregate in the outer query, the re-sort will probably destroy the ordering by b.code. regards, tom lane