Received: from maia.hub.org (maia-2.hub.org [200.46.204.251]) by mail.postgresql.org (Postfix) with ESMTP id 0E98F1336B42 for ; Sun, 6 Feb 2011 17:29:10 -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 60579-09 for ; Sun, 6 Feb 2011 21:29:02 +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 F25081337B82 for ; Sun, 6 Feb 2011 17:29:01 -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 p16LT15d015643; Sun, 6 Feb 2011 16:29:01 -0500 (EST) To: Mikkel Lauritsen cc: pgsql-performance@postgresql.org Subject: Re: Different execution plans for semantically equivalent queries In-reply-to: References: Comments: In-reply-to Mikkel Lauritsen message dated "Fri, 04 Feb 2011 16:22:02 +0100" Date: Sun, 06 Feb 2011 16:29:01 -0500 Message-ID: <15642.1297027741@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: 201102/271 X-Sequence-Number: 42409 Mikkel Lauritsen writes: > 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) I suspect that *any* database is going to have trouble optimizing that. You'd be well advised to lobby the persistence framework's authors to produce less brain-dead SQL. The NOT EXISTS formulation seems to express what's wanted much less indirectly. regards, tom lane