Received: from localhost (maia-2.hub.org [200.46.204.187]) by postgresql.org (Postfix) with ESMTP id 109469FA468 for ; Sun, 22 Jul 2007 21:02:29 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.187]) (amavisd-maia, port 10024) with ESMTP id 21228-08 for ; Sun, 22 Jul 2007 21:02:21 -0300 (ADT) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.5 Received: from ciao.gmane.org (main.gmane.org [80.91.229.2]) by postgresql.org (Postfix) with ESMTP id F41EA9FA213 for ; Sun, 22 Jul 2007 21:02:25 -0300 (ADT) Received: from list by ciao.gmane.org with local (Exim 4.43) id 1IClNW-00069q-7I for pgsql-sql@postgresql.org; Mon, 23 Jul 2007 02:02:22 +0200 Received: from 2109ds1-taa.0.fullrate.dk ([90.184.133.88]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Mon, 23 Jul 2007 02:02:22 +0200 Received: from nis by 2109ds1-taa.0.fullrate.dk with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Mon, 23 Jul 2007 02:02:22 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: =?ISO-8859-1?Q?Nis_J=F8rgensen?= Subject: Re: The nested view from hell - Restricting a subquerry Date: Mon, 23 Jul 2007 02:02:07 +0200 Lines: 22 Message-ID: References: <46A2CABF.3080108@obviously.com> <2385.1185127507@sss.pgh.pa.us> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit X-Complaints-To: usenet@sea.gmane.org X-Gmane-NNTP-Posting-Host: 2109ds1-taa.0.fullrate.dk User-Agent: Thunderbird 1.5.0.12 (Windows/20070509) In-Reply-To: <2385.1185127507@sss.pgh.pa.us> X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200707/128 X-Sequence-Number: 28863 Tom Lane skrev: >> PG apparently is not smart enough to recognize that the >> result of a max must be one of the values of the column (meaning that it >> can use an index) > > That's because it can't. As written, the query demands sums over groups > that *include* a specific invoice_id --- but each sum has to include > contributions from rows that could have another invoice_id. So the > condition on invoice_id cannot be pushed down to the individual scans. > If, in fact, the correct answer could be had by fetching only rows with > the specified invoice_id, then you need to fix the view to make that > clear. Well, the query can be satisfied by looking only at the rows with an order_id matching the invoice_id given. The condition that this is the largest invoice in the group then needs to be checked afterwards. I certainly did not expect the query planner to be able to deduce this, though. Nis