Skip site navigation (1) Skip section navigation (2)

Re: Picking out the most recent row using a time stamp column

From: Josh Berkus <josh(at)agliodbs(dot)com>
To: Dave Crooke <dcrooke(at)gmail(dot)com>
Cc: Kevin Grittner <Kevin(dot)Grittner(at)wicourts(dot)gov>, Michael Glaesemann <grzm(at)seespotcode(dot)net>, pgsql-performance(at)postgresql(dot)org
Subject: Re: Picking out the most recent row using a time stamp column
Date: 2011-02-25 00:20:00
Message-ID: 4D66F5B0.5080502@agliodbs.com (view raw or flat)
Thread:
Lists: pgsql-performance
On 2/24/11 3:38 PM, Dave Crooke wrote:
> Thanks to all .... I had a tickling feeling at the back of my mind that
> there was a neater answer here. For the record, times (all from
> in-memory cached data, averaged over a bunch of runs):
> 
> Dependent subquery = 117.9 seconds
> Join to temp table = 2.7 sec
> DISTINCT ON = 2.7 sec

But wait, there's more!  You haven't tested the Windowing Function
solution.  I'll bet it's even faster.


SELECT id_key, time_stamp, value
FROM (
	SELECT id_key, time_stamp, value,
		row_number()
		OVER ( PARTITION BY id_key
			ORDER BY time_stamp DESC)
 		as ranking
	FROM thetable
      ) as filtered_table
WHERE ranking = 1

-- 
                                  -- Josh Berkus
                                     PostgreSQL Experts Inc.
                                     http://www.pgexperts.com

In response to

Responses

pgsql-performance by date

Next:From: Shaun ThomasDate: 2011-02-25 00:58:33
Subject: Re: Picking out the most recent row using a time stamp column
Previous:From: Jochen ErwiedDate: 2011-02-25 00:03:12
Subject: Re: Possible parser bug? .... Re: Picking out the most recent row using a time stamp column

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group