Re: Distinct on a non-sort column

From: Cstdenis <lists(at)on-track(dot)ca>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Distinct on a non-sort column
Date: 2011-11-06 20:15:09
Message-ID: 4EB6EACD.3020505@on-track.ca
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 11/5/2011 4:11 PM, Tom Lane wrote:
> Cstdenis<lists(at)on-track(dot)ca> writes:
>> If I understand that you are proposing as
>> select * from
>> (select distinct on (user_id) * from stories as s order
>> by user_id) as foo
>> order by date_submitted desc limit 10;
> No, you always need to sort by *more* columns than are listed in
> DISTINCT ON. That's what determines which row is picked in each
> DISTINCT group. Read the SELECT reference page's example of how
> to use DISTINCT ON.
>
> regards, tom lane
>
Thanks. I was missing the obvious. This seems to give the results I need.

It's a shame the query parser isn't able to simply internally process
the query like that -- doing a second sort pass after the distinct
automatically in the case of the sort being on a different column from
distinct (instead of producing an error).

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Scott Marlowe 2011-11-06 21:27:19 Re: How to force some char type columns to be stored in uppercase
Previous Message Andrus 2011-11-06 19:58:56 How to force some char type columns to be stored in uppercase