Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id 134B81337BD4 for ; Fri, 4 Feb 2011 11:29:49 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 55470-01-3 for ; Fri, 4 Feb 2011 15:29:41 +0000 (UTC) X-Greylist: delayed 00:07:27.639696 by SQLgrey-1.7.6 Received: from mail.tala.dk (1503ds2-aroe.0.fullrate.dk [89.150.132.239]) by mail.postgresql.org (Postfix) with ESMTP id 2F5481337B9C for ; Fri, 4 Feb 2011 11:29:32 -0400 (AST) Received: from localhost.localdomain (server [127.0.0.1]) by mail.tala.dk (Postfix) with ESMTP id BFB68DDBB for ; Fri, 4 Feb 2011 16:22:02 +0100 (CET) Received: (from apache@localhost) by localhost.localdomain (8.14.4/8.14.4/Submit) id p14FM2nw012869; Fri, 4 Feb 2011 16:22:02 +0100 X-Authentication-Warning: localhost.localdomain: apache set sender to renard@tala.dk using -f To: Subject: Different execution plans for semantically equivalent queries X-PHP-Originating-Script: 0:func.inc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Date: Fri, 04 Feb 2011 16:22:02 +0100 From: Mikkel Lauritsen Message-ID: X-Sender: renard@tala.dk User-Agent: RoundCube Webmail/0.3.1 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.9 tagged_above=-10 required=5 tests=BAYES_00=-1.9 X-Spam-Level: X-Archive-Number: 201102/267 X-Sequence-Number: 42405 Hi all, I have a execution planner related issue that I'd like to have some help in understanding a bit deeper - I have a table which basically contains fields for a value, a timestamp and a record type which is an integer. I would like to do a query which retrieves the newest record for each type, and the persistence framework that I'm using does something which is structurally like SELECT * FROM table t1 WHERE 0 = (SELECT COUNT(*) FROM table t2 WHERE t2.type = t1.type AND t2.timestamp > t1.timestamp) On all of the PostgreSQL versions I've tried (9.0.2 included) this executes in about 20-30 seconds, which isn't exactly stellar. I've tried the (I think) equivalent SELECT * FROM table t1 WHERE NOT EXISTS (SELECT * FROM table t2 WHERE t2.type = t1.type AND t2.timestamp > t1.timestamp) instead, and that executes in about 100 ms, so it's about 200 times faster. The two statements have completely different execution plans, so I understand why there is a difference in performance, but as I'm unable to modify the SQL that the persistence framework generates I'd like to know if there's anything that I can do in order to make the first query execute as fast as the second one. I'm more specifically thinking whether I'm missing out on a crucial planner configuration knob or something like that, which causes the planner to treat the two cases differently. Best regards & thanks for an excellent database engine, Mikkel Lauritsen