X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id 964AA9DC953 for ; Tue, 20 Dec 2005 19:32:31 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 87098-07 for ; Tue, 20 Dec 2005 19:32:33 -0400 (AST) 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 2578D9DC80E for ; Tue, 20 Dec 2005 19:32:28 -0400 (AST) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.13.1/8.13.1) with ESMTP id jBKNVFTQ007210; Tue, 20 Dec 2005 18:31:15 -0500 (EST) To: John McCawley cc: pgsql-sql@postgresql.org Subject: Re: Performance of a view In-reply-to: <437B6974.5040803@hardgeus.com> References: <437B6974.5040803@hardgeus.com> Comments: In-reply-to John McCawley message dated "Wed, 16 Nov 2005 11:16:36 -0600" Date: Tue, 20 Dec 2005 18:31:15 -0500 Message-ID: <7209.1135121475@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=0.025 required=5 tests=[AWL=0.025] X-Spam-Score: 0.025 X-Spam-Level: X-Archive-Number: 200512/181 X-Sequence-Number: 23723 John McCawley writes: > I have a view which is defined as follows: > SELECT tbl_claim.claim_id, count(tbl_invoice.invoice_id) AS count, > min(tbl_invoice.invoicedate) AS invoicedate > FROM tbl_claim > LEFT JOIN tbl_invoice ON tbl_claim.claim_id = tbl_invoice.claim_id AND > tbl_invoice.active = 1 > GROUP BY tbl_claim.claim_id; > If I run: > EXPLAIN ANALYZE SELECT > tbl_claim.claim_id FROM tbl_claim INNER JOIN vw_claiminvoicecount ON > tbl_claim.claim_id = vw_claiminvoicecount.claim_id WHERE > tbl_claim.claim_id = 217778; > [ it's fast ] > However, if I run: > EXPLAIN ANALYZE SELECT > tbl_claim.claim_id FROM tbl_claim INNER JOIN vw_claiminvoicecount ON > tbl_claim.claim_id = vw_claiminvoicecount.claim_id WHERE > tbl_claim.claimnum = 'L1J8823'; > [ it's not ] I finally got around to looking at this. The reason the first case is fast is that the planner is able to deduce the extra condition vw_claiminvoicecount.claim_id = 217778, and then push that down into the view, so that the LEFT JOIN only need be performed for the single tbl_claim row with that claim_id. In the second case this is not possible --- the restriction on claimnum doesn't have any connection to the view that the planner can see. My advice is to extend the view to show claimnum as well, and then you can forget about the extra join of tbl_claim and just do SELECT * FROM vw_claiminvoicecount WHERE claimnum = 'L1J8823'; regards, tom lane