Re: selecting latest record

From: Rob Sargent <robjsargent(at)gmail(dot)com>
To: "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: selecting latest record
Date: 2009-09-22 14:09:26
Message-ID: 4AB8DA96.2090502@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Let's say there's an index on the date column: Does the where clause
approach necessarily out perform the distinct on version? Hoping the OP
has enough data to make analyse useful.

A. Kretschmer wrote:
> In response to Louis-David Mitterrand :
>
>> Hi,
>>
>> I have a simple table
>>
>> price(id_product, price, date)
>>
>> which records price changes for each id_product. Each time a price
>> changes a new tuple is created.
>>
>> What is the best way to select only the latest price of each id_product?
>>
>
> There are several ways to do that, for instance with DISTINCT ON (only
> postgresql):
>
> test=*# select * from price ;
> id_product | price | datum
> ------------+-------+------------
> 1 | 10 | 2009-09-01
> 1 | 12 | 2009-09-10
> 2 | 11 | 2009-09-10
> 2 | 8 | 2009-09-13
> (4 rows)
>
> test=*# select distinct on (id_product) id_product, price from price order by id_product, datum desc;
> id_product | price
> ------------+-------
> 1 | 12
> 2 | 8
> (2 rows)
>
> Andreas
>

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message hfdabler 2009-09-22 14:23:14 Data integration tool in Chinese?
Previous Message A. Kretschmer 2009-09-22 10:08:46 Re: selecting latest record