Re: [SQL] Finding the "most recent" rows

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Brook Milligan <brook(at)trillium(dot)NMSU(dot)Edu>
Cc: pgsql-sql(at)postgreSQL(dot)org
Subject: Re: [SQL] Finding the "most recent" rows
Date: 1999-04-23 16:29:28
Message-ID: 21889.924884968@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Brook Milligan <brook(at)trillium(dot)NMSU(dot)Edu> writes:
> Tom Lane wrote:
>>
>> SELECT DISTINCT ON place * FROM table ORDER BY place, time DESC;
>>
>> might do the right thing. It *seems* to select the first row for each
>> value of place. I've never seen a spec for this feature, however, so
>> I'm not sure if it's reliable or not...

> Cool idea. Is DISTINCT guarranteed to choose the first row that
> matches or can it choose any row?

I dunno, that's why I said I was unsure that this method was reliable.
By experimentation it seems that Postgres' DISTINCT code works that way,
but I have no idea whether the SQL spec mandates it or allows any row
within a group to be chosen.

I recall now that when I first heard of "SELECT DISTINCT ON field"
I objected that the results weren't well-defined (since it's not clear
how DISTINCT will choose which tuple to return). It might be that the
SQL spec requires the first tuple to be chosen for each value of
"field", which would allow the user to control the results by inserting
a preceding ORDER BY step --- or skip the ORDER BY, if he doesn't really
care which tuple he gets. That'd actually be a pretty cool design.
Anyone have an SQL spec handy to check it?

regards, tom lane

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Bruce Momjian 1999-04-23 19:43:11 Re: [HACKERS] Re: [SQL] Finding the "most recent" rows
Previous Message Tom Lane 1999-04-23 16:06:09 Re: [SQL] Finding the "most recent" rows