Re: Advanced SELECT

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Richard Huxton <dev(at)archonet(dot)com>
Cc: Kai Hessing <kai(dot)hessing(at)hobsons(dot)de>, pgsql-sql(at)postgresql(dot)org
Subject: Re: Advanced SELECT
Date: 2005-02-24 15:32:16
Message-ID: 25016.1109259136@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-sql

Richard Huxton <dev(at)archonet(dot)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) ss
group by key1 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

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2005-02-24 15:42:01 Re: Fedora postgresql not starting
Previous Message Geoffrey KRETZ 2005-02-24 15:00:52 PGS 7.4.x PREPARE statement

Browse pgsql-sql by date

  From Date Subject
Next Message Joel Fradkin 2005-02-24 15:47:50 Re: Speeds using a transaction vrs not
Previous Message Aarni Ruuhimäki 2005-02-24 15:17:14 Read count ?