Re: Advanced SELECT - Mailing list pgsql-sql

From Tom Lane
Subject Re: Advanced SELECT
Date
Msg-id 25016.1109259136@sss.pgh.pa.us
Whole thread Raw
In response to Re: Advanced SELECT  (Richard Huxton <dev@archonet.com>)
Responses Re: Advanced SELECT  (Kai Hessing <kai.hessing@hobsons.de>)
List pgsql-sql
Richard Huxton <dev@archonet.com> writes:
> Search the mailing-list archives for "custom aggregate concat" and 
> you'll quickly find an example of how to write your own custom aggregate 
> (like SUM()).

> Warning - I don't think you can guarantee the order of elements in the 
> aggregated sectors.

In recent PG versions you can.  For example,
select key1, custom_aggregate(detail_field) from(select key1, detail_field from my_table order by key1, key2) ssgroup
bykey1 order by key1;
 

The detail_field values will be fed to the aggregate in order by key2
within each key1 group.  This is one of the examples that motivated
allowing ORDER BY in subselects, even though it's outside the SQL spec.

[ experiments... ]  This works reliably in 7.4 and up.  Before that,
the optimizer didn't make the connection between the sort ordering of
the inner query and that needed by the outer, so it would repeat the
sort step using only key1 and very possibly destroy the key2 ordering.
        regards, tom lane


pgsql-sql by date:

Previous
From: Aarni Ruuhimäki
Date:
Subject: Read count ?
Next
From: "Joel Fradkin"
Date:
Subject: Re: Speeds using a transaction vrs not