26
Selecting the Optimal Plan
Exploring Plans
Join order, join methods, access methods
A full scan where possible; with numerous options, the search space is
reduced.
Simple Queries and Prepared Statements
Optimizing retrieval of all rows
Minimum total cost
Cursors
Optimizing retrieval of a portion of the first rows
Minimum cost for cursor_tuple_fraction rows
The optimizer tries to evaluate all possible query execution plans to choose
the best one.
A dynamic programming algorithm is used to reduce the search space, but
when the number of options is high—especially due to the number of tables
being joined—finding an exact solution to the optimization problem becomes
impractical within a reasonable time. In such cases, the planner reduces the
number of plans it evaluates by either not considering all pairwise join
options or switching to a genetic optimization algorithm (GEQO - Genetic
Query Optimization). This could result in the optimizer choosing a
suboptimal plan not because of evaluation errors, but merely because the
best plan wasn't considered.
What defines the "best plan"?
For typical queries, the optimal plan minimizes the resources needed to
retrieve all rows, meaning it has the lowest total cost.
However, when using cursors, it's important to retrieve the first rows as soon
as possible. Therefore, there's a parameter cursor_tuple_fractio (default 0.1)
that determines the fraction of rows to be retrieved as quickly as possible.
The lower the parameter value, the more the initial cost influences the plan
selection instead of the total cost.