Very slow query performance when using CTE

From: Chris Joysn <joysn71(at)gmail(dot)com>
To: pgsql-performance(at)lists(dot)postgresql(dot)org
Subject: Very slow query performance when using CTE
Date: 2025-04-01 13:37:51
Message-ID: CAKRYhW36jEbPPSPoiPkNcPWdrEXOtdugw9Hyg1poHju7LECHJg@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance

Hello,
I have an issue when using CTEs. A query, which consists of multiple CTEs,
runs usually rather fast (~5s on my environment). But it turned out that
using one CTE can lead to execution times of up to one minute.
That CTE is used two times within the query. In the CTE there are 2600
rows, compared to results of the other CTEs its a fraction of the data.
When replacing this CTE and use the original table instead in the jions,
the query performs nicely.
However, it is not always like this. Running the same query on a almost
same set of data, quantity wise, may give indeed good performance when
using that CTE.
This is the slow performing query using CTE:
https://explain.dalibo.com/plan/45ce86d9cfge14c7
And this is the fast performing query without that CTE:
https://explain.dalibo.com/plan/4abgc4773gg349b4

The query runs on the very same environment and data.
What can be the issue here and how can I address it?

Responses

Browse pgsql-performance by date

  From Date Subject
Next Message Tom Lane 2025-04-01 14:28:58 Re: Very slow query performance when using CTE
Previous Message Dimitrios Apostolou 2025-03-29 00:48:49 Re: parallel pg_restore blocks on heavy random read I/O on all children processes