pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Michael Fuhr <mike@fuhr.org>
Cc: Steven Murdoch <psql+Steven.Murdoch@cl.cam.ac.uk>
Cc: pgsql-sql@postgresql.org
Subject: Re: Sorting items in aggregate function
Date: Tue, 12 Sep 2006 16:37:55 -0400
Message-ID: <21365.1158093475@sss.pgh.pa.us> (raw)
In-Reply-To: <20060912181759.GA66966@winnie.fuhr.org>
References: <20060912154628.GB4991@cl.cam.ac.uk>
	<20060912181759.GA66966@winnie.fuhr.org>

Michael Fuhr <mike@fuhr.org> 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



view thread (5+ messages)  latest in thread

Message-ID: <21365.1158093475@sss.pgh.pa.us>
Permalink:  ../21365.1158093475@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/21365.1158093475@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, mike@fuhr.org, psql+Steven.Murdoch@cl.cam.ac.uk
  Subject: Re: Sorting items in aggregate function
  In-Reply-To: <21365.1158093475@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