Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id 832C01337B69 for ; Thu, 24 Feb 2011 16:19:11 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.29]) (amavisd-maia, port 10024) with ESMTP id 74795-04 for ; Thu, 24 Feb 2011 20:19:04 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from gw.wicourts.gov (gwmta.wicourts.gov [165.219.244.99]) by mail.postgresql.org (Postfix) with ESMTP id AE0FF1337B4E for ; Thu, 24 Feb 2011 16:19:03 -0400 (AST) Received: from Courts-MTA by gw.wicourts.gov with Novell_GroupWise; Thu, 24 Feb 2011 14:19:03 -0600 Message-Id: <4D6668CF020000250003AFC9@gw.wicourts.gov> X-Mailer: Novell GroupWise Internet Agent 8.0.1 Date: Thu, 24 Feb 2011 14:18:55 -0600 From: "Kevin Grittner" To: "Dave Crooke" , "pgsql-performance" Subject: Re: Picking out the most recent row using a time stamp column References: In-Reply-To: Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit Content-Disposition: inline X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-4.21 tagged_above=-10 required=5 tests=BAYES_00=-1.9, RCVD_IN_DNSWL_MED=-2.3, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201102/479 X-Sequence-Number: 42617 Dave Crooke wrote: > create table data > (id_key int, > time_stamp timestamp without time zone, > value double precision); > > create unique index data_idx on data (id_key, time_stamp); > I need to find the most recent value for each distinct value of > id_key. Well, unless you use timestamp WITH time zone, you might not be able to do that at all. There are very few places where timestamp WITHOUT time zone actually makes sense. > There is no elegant (that I know of) syntax for this How about this?: select distinct on (id_key) * from data order by id_key, time_stamp; > select > a.id_key, a.time_stamp, a.value > from > data a > where > a.time_stamp= > (select max(time_stamp) > from data b > where a.id_key=b.id_key) Rather than the above, I typically find this much faster: select a.id_key, a.time_stamp, a.value from data a where not exists (select * from data b where b.id_key=a.id_key and b.time_stamp > a.time_stamp) -Kevin