X-Original-To: pgsql-performance-postgresql.org@localhost.postgresql.org Received: from localhost (av.hub.org [200.46.204.144]) by postgresql.org (Postfix) with ESMTP id 4861F9DCA84 for ; Wed, 8 Feb 2006 11:46:44 -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 77836-06 for ; Wed, 8 Feb 2006 11:46:48 -0400 (AST) X-Greylist: from auto-whitelisted by SQLgrey- Received: from megazone.bigpanda.com (megazone.bigpanda.com [64.147.171.210]) by postgresql.org (Postfix) with ESMTP id 05E3A9DCA41 for ; Wed, 8 Feb 2006 11:46:41 -0400 (AST) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id D307E3AF48; Wed, 8 Feb 2006 07:46:39 -0800 (PST) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id D11783AF2F; Wed, 8 Feb 2006 07:46:39 -0800 (PST) Date: Wed, 8 Feb 2006 07:46:39 -0800 (PST) From: Stephan Szabo To: Jacob Costello Cc: pgsql-performance@postgresql.org Subject: Re: optimizing away join when querying view In-Reply-To: <1139406891.11389.60.camel@localhost.localdomain> Message-ID: <20060208073955.S43207@megazone.bigpanda.com> References: <1139406891.11389.60.camel@localhost.localdomain> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, score=0.139 required=5 tests=[AWL=0.139] X-Spam-Score: 0.139 X-Spam-Level: X-Archive-Number: 200602/69 X-Sequence-Number: 17055 On Wed, 8 Feb 2006, Jacob Costello wrote: > Postgres doesn't seem to optimize away unnecessary joins in a view > definition when the view is queried in such a way that the join need not > be executed. In the example below, I define two tables, foo and bar, > with a foreign key on bar referencing foo, and a view on the natural > join of the tables. The tables are defined so that the relationship > from bar to foo is allowed to be many to one, with the column of bar > referencing foo (column a) set NOT NULL, so that there must be exactly > one foo record for every bar record. I then EXPLAIN selecting the "b" > column from bar, through the view and from bar directly. The tables > have been ANALYZEd but have no data. EXPLAIN shows the join actually > occurring when selecting b from the view quux. If I understand > correctly (maybe I don't), this is guaranteed to be exactly the same as > the selecting b directly from the bar table. AFAIK there are periods in which a foreign key does not guarantee that there's one foo record for every bar record between an action and the constraint check for that action at statement end so you'd probably have to be careful in any case.