Re: select distinct on - Mailing list pgsql-general

From Tom Lane
Subject Re: select distinct on
Date
Msg-id 13756.974761789@sss.pgh.pa.us
Whole thread Raw
In response to select distinct on  (Dave Ahn <ahn@vec.wfubmc.edu>)
List pgsql-general
Dave Ahn <ahn@vec.wfubmc.edu> writes:
> Clearly this does not work:
>     SELECT DISTINCT ON (f1) * from table ORDER BY f2, f3, f1

No; the implementation of DISTINCT requires the DISTINCT fields to be
the major sort keys, so you have to ORDER BY f1,f2,f3 instead.

If you want the final output sorted differently, in 7.0 you don't really
have much choice but to do the SELECT DISTINCT into a temporary table.
In 7.1 it'll be possible to do it via subselect-in-FROM:

    SELECT * FROM
      (SELECT DISTINCT ON (f1) * FROM table ORDER BY f1, f2, f3) tmp
    ORDER BY f2, f3, f1;

but in 7.0 there's no way to cause the system to do multiple sorting
passes in one query.

            regards, tom lane

pgsql-general by date:

Previous
From: Tom Lane
Date:
Subject: Re: External Large objects what became of them
Next
From: "Jason"
Date:
Subject: trying to move from MySQL