X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id 2CCB29F9CD8 for ; Mon, 22 May 2006 20:07:37 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 48681-07 for ; Mon, 22 May 2006 20:07:27 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by postgresql.org (Postfix) with ESMTP id 7AD379F9B14 for ; Mon, 22 May 2006 20:07:27 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.13.6/8.13.6) with ESMTP id k4MN7O74015853; Mon, 22 May 2006 19:07:24 -0400 (EDT) To: "Tim Jones" cc: pgsql-performance@postgresql.org Subject: Re: slow query using sub select In-reply-to: <47668A1334CDBF46927C1A0DFEB223D340EED2@mail.optiosoftware.com> References: <47668A1334CDBF46927C1A0DFEB223D340EED2@mail.optiosoftware.com> Comments: In-reply-to "Tim Jones" message dated "Mon, 22 May 2006 18:11:07 -0400" Date: Mon, 22 May 2006 19:07:24 -0400 Message-ID: <15852.1148339244@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200605/425 X-Sequence-Number: 19212 "Tim Jones" writes: > I am having a problem with a sub select query being kinda slow. The > query is as follows: > select batterycode, batterydescription, observationdate from Battery t1 > where patientidentifier=611802158 and observationdate = (select > max(observationdate) from Battery t2 where t2.batterycode=t1.batterycode > and patientidentifier=611802158) order by batterydescription. Yeah, this is essentially impossible for the planner to optimize, because it doesn't see any way to de-correlate the subselect, so it does it over again for every row. You might find it works better if you cast the thing as a SELECT DISTINCT ON problem (look at the "weather report" example in the SELECT reference page). regards, tom lane