Brook Milligan <brook@trillium.NMSU.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