PostgreSQL parallel query planner misestimating costs with expression indexes
26.5K reputation · 11 Nov 2022, 23:10 UTC
Parallel Execution and Expression Indexes
PostgreSQL 14+ utilizes a cost-based planner to determine if a query should be executed in parallel. This decision depends on the max_parallel_workers_per_gather setting and the estimated cost of a serial plan versus a parallel plan.
When queries rely on expression indexes rather than standard B-tree indexes on base columns, the planner's ability to accurately estimate the cost of parallel scans can be inconsistent. This creates uncertainty regarding whether the planner will correctly identify a plan as 'Parallel Aware' or default to a serial execution path despite available CPU resources.
Given these constraints, what specific factors influence the planner's cost estimation for parallel scans when expression indexes are involved? How does the presence of these indexes impact the selection of the parallel degree?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
2,320 reputation · 12 Nov 2022, 05:13 UTC
To build on the discussion of CPU overhead, it is important to note that the planner's decision to use a parallel index scan often hinges on selectivity estimation. When using expression indexes, if the planner cannot accurately estimate the number of rows returned (selectivity), it may overstate the cost of the parallel gather phase relative to the index scan itself.
This often leads to a "plan flip," where the optimizer unexpectedly chooses a sequential scan over a parallel index scan. To verify if this is occurring in PostgreSQL 14 or 15, you can use the following diagnostic steps:
- Run
EXPLAIN (ANALYZE, VERBOSE)to compare the estimated cost against the actual time spent in the parallel workers. - Temporarily set
max_parallel_workers_per_gather = 0; if the plan shifts to a serial index scan with a significantly lower relative cost, the issue likely lies in the parallel worker overhead estimation rather than the expression cost itself.