pg.ddx.io  pgsql-performance@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Kevin Grittner <Kevin.Grittner@wicourts.gov>
To: Dave Crooke <dcrooke@gmail.com>
To: pgsql-performance <pgsql-performance@postgresql.org>
Subject: Re: Picking out the most recent row using a time stamp column
Date: Thu, 24 Feb 2011 14:18:55 -0600
Message-ID: <4D6668CF020000250003AFC9@gw.wicourts.gov> (raw)
In-Reply-To: <AANLkTinTgU-jfPOhrfteBvhAhgG_8zknpk13N9L4QMap@mail.gmail.com>
References: <AANLkTinTgU-jfPOhrfteBvhAhgG_8zknpk13N9L4QMap@mail.gmail.com>

Dave Crooke <dcrooke@gmail.com> 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



view thread (20+ messages)  latest in thread

Message-ID: <4D6668CF020000250003AFC9@gw.wicourts.gov>
Permalink:  ../4D6668CF020000250003AFC9@gw.wicourts.gov/
Also on:    postgresql.org/message-id/4D6668CF020000250003AFC9@gw.wicourts.gov

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-performance@postgresql.org
  Cc: Kevin.Grittner@wicourts.gov, dcrooke@gmail.com
  Subject: Re: Picking out the most recent row using a time stamp column
  In-Reply-To: <4D6668CF020000250003AFC9@gw.wicourts.gov>
  References: <AANLkTinTgU-jfPOhrfteBvhAhgG_8zknpk13N9L4QMap@mail.gmail.com> <4D6668CF020000250003AFC9@gw.wicourts.gov>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox