Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id 717151337990 for ; Fri, 14 Jan 2011 19:40:53 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.251]) (amavisd-maia, port 10024) with ESMTP id 90169-04 for ; Fri, 14 Jan 2011 23:40:45 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id 53AC21336B42 for ; Fri, 14 Jan 2011 19:40:45 -0400 (AST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id p0ENehid014114; Fri, 14 Jan 2011 18:40:43 -0500 (EST) To: "Kevin Grittner" cc: "Nikolas Everett" , sthomas@peak6.com, "pgsql-performance@postgresql.org" Subject: Re: Best way to get the latest revision from a table In-reply-to: <4D3088E70200002500039632@gw.wicourts.gov> References: <4D30D708.3020704@peak6.com> <4D3088E70200002500039632@gw.wicourts.gov> Comments: In-reply-to "Kevin Grittner" message dated "Fri, 14 Jan 2011 17:33:27 -0600" Date: Fri, 14 Jan 2011 18:40:43 -0500 Message-ID: <14113.1295048443@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-10 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201101/114 X-Sequence-Number: 41901 "Kevin Grittner" writes: > Shaun Thomas 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