pg.ddx.io  pgsql-performance@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Kevin Grittner <Kevin.Grittner@wicourts.gov>
Cc: Nikolas Everett <nik9000@gmail.com>
Cc: sthomas@peak6.com, "pgsql-performance@postgresql.org" <pgsql-performance@postgresql.org>
Subject: Re: Best way to get the latest revision from a table
Date: Fri, 14 Jan 2011 18:40:43 -0500
Message-ID: <14113.1295048443@sss.pgh.pa.us> (raw)
In-Reply-To: <4D3088E70200002500039632@gw.wicourts.gov>
References: <AANLkTikVZG_Us9R9iLdz=GnqqEnHE5D7Go9xkENkdGiQ@mail.gmail.com>
	<4D30D708.3020704@peak6.com>
	<4D3088E70200002500039632@gw.wicourts.gov>

"Kevin Grittner" <Kevin.Grittner@wicourts.gov> writes:
> Shaun Thomas <sthomas@peak6.com> wrote:
>> This actually looks like a perfect candidate for DISTINCT ON.
>> 
>> SELECT DISTINCT ON (a, b) a, b, revision
>> FROM test
>> ORDER BY a, b DESC;
 
> I wouldn't say perfect.  It runs about eight times slower than what
> I suggested and returns a fairly random value for revision instead
> of the max(revision).

Shaun's example is a bit off: normally, when using DISTINCT ON, you want
an ORDER BY key that uses all the given DISTINCT keys and then some
more.  To get the max revision for each a/b combination it ought to be

SELECT DISTINCT ON (a, b) a, b, revision
   FROM test
   ORDER BY a, b, revision DESC;

As for speed, either one might be faster in a particular situation.

			regards, tom lane



view thread (13+ messages)  latest in thread

Message-ID: <14113.1295048443@sss.pgh.pa.us>
Permalink:  ../14113.1295048443@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/14113.1295048443@sss.pgh.pa.us

 · 

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 using the --to and --cc options:
  reply via email

  To: pgsql-performance@postgresql.org
  Cc: tgl@sss.pgh.pa.us, Kevin.Grittner@wicourts.gov, nik9000@gmail.com
  Subject: Re: Best way to get the latest revision from a table
  In-Reply-To: <14113.1295048443@sss.pgh.pa.us>

* 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