Re: BUG #17721: A completely unused CTE negatively affect Query Plan - Mailing list pgsql-bugs

From Nathaniel Hazelton
Subject Re: BUG #17721: A completely unused CTE negatively affect Query Plan
Date
Msg-id BD7EBA1F-4FB7-43CC-A70B-42439454EAE5@sturdyai.com
Whole thread Raw
In response to Re: BUG #17721: A completely unused CTE negatively affect Query Plan  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-bugs
The CTE in that location was emulating a view in which we have a CTE - which responds the same way.  Does this mean
CTEscan never be used in views that could be flattened without affecting performance?  I'm able to find any mention of
this. The only mention of CTEs being optimization fences goes back when all CTEs were materialized.
 

Is there some way to know when it is safe or not to use a CTE in a view / subquery?  It would be great to have some
documentationon that.
 

On 12/14/22, 11:25 AM, "Tom Lane" <tgl@sss.pgh.pa.us <mailto:tgl@sss.pgh.pa.us>> wrote:


PG Bug reporting form <noreply@postgresql.org <mailto:noreply@postgresql.org>> writes:
> I've boiled down an issue we have in production to a simple query that can
> demonstrate it. I've run this on 13,14 and 15 locally in a docker container
> with the same results. If a CTE that is completely unexecuted exists in a
> subquery (or view in our production case) it affects the query plan VERY
> negatively. The first explain shows a sequential scan, where the second
> explain shows an index scan, just by the existence of the (obviously)
> unexecuted CTE.


The presence of the CTE prevents flattening of the subquery.
If you don't like it, don't attach the CTE right there.


regards, tom lane




pgsql-bugs by date:

Previous
From: Mats Kindahl
Date:
Subject: Re: Crash during backend start when low on memory
Next
From: Daniel Gustafsson
Date:
Subject: Re: BUG #17720: pg_dump creates a dump with primary key that cannot be restored, when specifying 'using index ...'