Re: DISTINCT ON without ORDER BY

From: Gregory Stark <stark(at)enterprisedb(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: DISTINCT ON without ORDER BY
Date: 2009-04-20 10:29:16
Message-ID: 87ocurwrcz.fsf@oxford.xeocode.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Martijn van Oosterhout <kleptog(at)svana(dot)org> writes:

> SELECT * FROM foo
> WHERE id in (SELECT max(id) FROM foo GROUP BY bar);
>
> Is there a way to acheive the above result without a sort and without a
> self-join?

Something like

SELECT bar, (magic_agg_func(foo)).* FROM foo GROUP BY bar

where you define an aggregate function magic_agg_func to remember the whole
record for the largest value of id. Something like:

postgres=# create function magic_transition(a,a) returns a as 'select case when $1.aid > $2.aid then $1 else $2 end' language sql;
postgres=# create aggregate magic (a) (sfunc = magic_transition, stype = a);

Not sure it'll be faster though.

--
Gregory Stark
EnterpriseDB http://www.enterprisedb.com
Ask me about EnterpriseDB's On-Demand Production Tuning

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Gregory Stark 2009-04-20 10:32:25 Re: Nooby Q: Should this take five hours? And counting?
Previous Message Alban Hertroys 2009-04-20 08:53:46 Re: Frequently unable connecting to db "server doesn't listen"