Re: simple query question: return latest

From: Michael Fuhr <mike(at)fuhr(dot)org>
To: Scott Frankel <leknarf(at)pacbell(dot)net>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: simple query question: return latest
Date: 2004-11-12 03:13:02
Message-ID: 20041112031302.GA46532@winnie.fuhr.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Nov 11, 2004 at 05:00:46PM -0800, Scott Frankel wrote:

> How does one return the latest row from a table, given multiple entries
> of varying data?
> i.e.: given a table that looks like this:
>
> color | date
> --------+------------
> red | 2004-01-19
> blue | 2004-05-24
> red | 2004-04-12
> blue | 2004-05-24
>
> How do I select the most recent entry for 'red'?

One way would be to sort by date and use a LIMIT clause:

SELECT * FROM colortable WHERE color = 'red' ORDER BY date DESC LIMIT 1;

If you want the most recent entry for all colors then you could use
SELECT DISTINCT ON:

SELECT DISTINCT ON (color) * FROM colortable ORDER BY color, date DESC;

In either case, if multiple records have the same date and the ORDER BY
clause isn't specific enough to guarantee a certain order, then it's
indeterminate which record you'll get.

--
Michael Fuhr
http://www.fuhr.org/~mfuhr/

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Bruce Momjian 2004-11-12 04:01:56 Re: GUC custom variables broken
Previous Message Stephan Szabo 2004-11-12 02:46:46 Re: simple query question: return latest