Re: Distinct on a non-sort column

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

Cstdenis <lists(at)on-track(dot)ca> writes:
> I am trying to write a query that selects recent submissions (sorted by
> submission_date) but only selects the most recent one for each user_id.

> example query: /select distinct on (user_id) * from stories order by
> date_submitted desc limit 10;/

> However postgres will not allow me to filter out duplicate rows with
> distinct unless I sort on that column, which would product useless
> results for me.

Do the DISTINCT ON in a sub-query, with an ORDER BY appropriate for that
task, and then re-sort the rows the way you want them presented in the
outer query.

SELECT ... FROM
(SELECT DISTINCT ON ... ORDER BY ...) ss
ORDER BY ...;

regards, tom lane

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message John R Pierce 2011-11-05 19:58:22 Re: Distinct on a non-sort column
Previous Message Tair Sabirgaliev 2011-11-05 19:38:52 Re: Distinct on a non-sort column