Received: from malur.postgresql.org ([217.196.149.56]) by arkaria.postgresql.org with esmtp (Exim 4.84_2) (envelope-from ) id 1bAOli-0000S8-Hc for pgsql-admin@arkaria.postgresql.org; Tue, 07 Jun 2016 21:42:38 +0000 Received: from localhost ([127.0.0.1] helo=postgresql.org) by malur.postgresql.org with smtp (Exim 4.84_2) (envelope-from ) id 1bAOlh-00081U-TO for pgsql-admin@arkaria.postgresql.org; Tue, 07 Jun 2016 21:42:37 +0000 Received: from makus.postgresql.org ([2001:4800:1501:1::229]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1bAOk2-00065z-Ce for pgsql-admin@postgresql.org; Tue, 07 Jun 2016 21:40:54 +0000 Received: from sss.pgh.pa.us ([66.207.139.130]) by makus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.84_2) (envelope-from ) id 1bAOk0-0006sx-3r for pgsql-admin@postgresql.org; Tue, 07 Jun 2016 21:40:53 +0000 Received: from sss1.sss.pgh.pa.us (localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.4/8.14.4) with ESMTP id u57Leptu014299; Tue, 7 Jun 2016 17:40:51 -0400 From: Tom Lane To: Max Kremer cc: pgsql-admin@postgresql.org Subject: Re: Planner is ignoring index when view is queried but uses index when running underlying view's sql In-reply-to: References: Comments: In-reply-to Max Kremer message dated "Tue, 07 Jun 2016 15:45:21 -0400" Date: Tue, 07 Jun 2016 17:40:51 -0400 Message-ID: <14298.1465335651@sss.pgh.pa.us> X-Pg-Spam-Score: -3.3 (---) List-Archive: List-Help: List-ID: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: X-Mailing-List: pgsql-admin Precedence: bulk Sender: pgsql-admin-owner@postgresql.org Max Kremer writes: > I've encountered a very strange result when using a view in a query VS the > underlying sql of the view. When accessing the view I get a different query > plan than running the sql that makes up the view. Using the view is 10x > slower and generates a strange query plan that seems to ignore > the existence of an index. I believe the problem is that the WITH attached to the view's SELECT prevents the view sub-select from being flattened into the outer query (ie, this is another way in which WITH acts as an optimization fence). So the sub-select is planned without awareness of the ORDER BY/LIMIT that would encourage picking a suitably ordered join plan. Try writing the CTE as a plain sub-select, instead. (AFAIR, this behavior just stems from a lack of round tuits and not any fundamental difficulty: the WITHs could perfectly well be hoisted up to the outer query. But don't hold your breath waiting for that to happen.) (BTW, what PG version is that?) regards, tom lane -- Sent via pgsql-admin mailing list (pgsql-admin@postgresql.org) To make changes to your subscription: http://www.postgresql.org/mailpref/pgsql-admin