Upgrading a PostgreSQL database to a new major version can improve query performance, but it can also change how existing SQL statements are executed. A query that previously used an index scan may start using a sequential scan. A join that previously used a nested loop may switch to a hash join. Sometimes these changes improve performance, but in other situations they can make frequently executed queries slower.
This happens because PostgreSQL's query planner continuously evaluates different execution strategies and selects the plan it estimates will be the most efficient. The planner considers table statistics, available indexes, estimated row counts, configuration settings, and the cost of different operations.
PostgreSQL 19 introduces additional query optimization improvements and new tools for understanding and controlling execution plans. One important addition is the pg_plan_advice extension, which allows developers and database administrators to inspect planner decisions, experiment with alternative plans, and stabilize selected planning decisions when necessary. PostgreSQL 19 also provides pg_stash_advice, which can automatically apply stored plan advice to queries based on their query identifiers.
For applications moving from PostgreSQL 18 to PostgreSQL 19, reviewing changed execution plans is an important part of performance validation. This article explains how to identify queries with changed plans, compare execution behavior, investigate performance differences, and use PostgreSQL 19's new plan advice capabilities.
Why Query Plans Change After a PostgreSQL Upgrade
PostgreSQL does not execute every SQL statement in the same way. Before executing a query, the planner evaluates possible execution strategies and selects one based on estimated costs.
Consider the following query:
SELECT
order_id,
customer_id,
order_date,
total_amount
FROM orders
WHERE customer_id = 1050;If the orders table contains millions of records and an index exists on customer_id, PostgreSQL may choose an index scan.
However, if the query returns a large percentage of the table, a sequential scan may be more efficient because reading the table directly can cost less than accessing many individual index entries.
The planner makes this decision using statistics and cost estimates.
After upgrading to PostgreSQL 19, the planner may choose a different strategy because of changes in optimizer logic, statistics, configuration, or the underlying data.
PostgreSQL 19 includes several planner improvements, including:
- More opportunities to convert NOT IN conditions into anti-joins when NULL values are not present.
- Improved optimization of certain LEFT JOIN operations.
- Better handling of semijoins.
- Additional opportunities to perform aggregation before joins.
- Improved hash join handling for NULL join keys.
- Additional incremental sort planning opportunities.
These changes can produce better plans for many workloads, but they can also change the execution strategy of existing application queries.
A different plan is not automatically a problem. The important question is whether the new plan performs better or worse for the application's actual workload.
Capturing Query Performance Before and After the Upgrade
The most reliable way to identify plan regressions is to capture execution information before upgrading and compare it with the results after moving to PostgreSQL 19.
For example, an application may have a frequently executed order search query. Before upgrading, record its execution plan, execution time, returned rows, and buffer activity.
After upgrading, execute the same query with representative parameter values and compare the results.
Make sure both environments use comparable data, indexes, configuration settings, and workload conditions. Otherwise, a performance difference may come from environmental changes rather than the PostgreSQL version itself.
Using EXPLAIN ANALYZE
PostgreSQL provides EXPLAIN to display the execution plan selected for a SQL statement.
The following command captures actual execution information:
EXPLAIN (
ANALYZE,
BUFFERS,
SETTINGS,
VERBOSE
)
SELECT
order_id,
customer_id,
order_date,
total_amount
FROM orders
WHERE customer_id = 1050;Each option provides different information:
| Option | Purpose |
|---|---|
| ANALYZE | Executes the query and reports actual execution statistics |
| BUFFERS | Shows shared, local, and temporary buffer activity |
| SETTINGS | Displays relevant non-default planner settings |
| VERBOSE | Provides additional details about the execution plan |
The output includes estimated and actual row counts, execution time, planning time, and information about the operations used by PostgreSQL.
One important point is that EXPLAIN ANALYZE actually executes the statement. For SELECT queries, this can still trigger side effects if the statement calls functions that modify data or perform external operations. Use a safe test environment when necessary.
Saving Execution Plans as JSON
Text output is useful for manual inspection, but JSON makes it easier to store and process execution plans.
EXPLAIN (
ANALYZE,
BUFFERS,
SETTINGS,
FORMAT JSON
)
SELECT
order_id,
customer_id,
order_date,
total_amount
FROM orders
WHERE customer_id = 1050;A JSON execution plan can be saved as a migration artifact and compared using a script or performance analysis tool.
The comparison should focus on important plan properties rather than expecting the entire JSON output to remain identical. Costs, timings, buffer counts, and other runtime values naturally change between executions.
Identifying Queries With Performance Changes
PostgreSQL provides the pg_stat_statements extension for collecting statistics about SQL statements executed by the server.
It records information such as execution count, total execution time, average execution time, returned rows, and buffer activity.
The extension must be loaded through shared_preload_libraries because it requires shared memory. This requires a server restart when it is added to an existing configuration. Query identifier calculation must also be enabled.
After configuring the extension, create it in the database:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;Enable planning statistics if planning time is also important:
ALTER SYSTEM SET pg_stat_statements.track_planning = on;The configuration change takes effect according to the parameter's context and may require a reload or restart. Verify the active setting before collecting measurements.
Finding Expensive Queries
The following query identifies statements with high total execution time:
SELECT
queryid,
calls,
ROUND(total_exec_time::numeric, 2)
AS total_exec_ms,
ROUND(mean_exec_time::numeric, 2)
AS average_exec_ms,
rows,
shared_blks_hit,
shared_blks_read,
query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;This report helps identify queries that consume a large amount of database execution time.
For a different perspective, sort by average execution time:
SELECT
queryid,
calls,
ROUND(mean_exec_time::numeric, 2)
AS average_exec_ms,
ROUND(max_exec_time::numeric, 2)
AS maximum_exec_ms,
query
FROM pg_stat_statements
WHERE calls > 10
ORDER BY mean_exec_time DESC
LIMIT 20;A query with a high average execution time may deserve attention even if it is not executed frequently.
For upgrade comparisons, collect statistics over equivalent workload periods on both versions. Remember that pg_stat_statements counters are cumulative and can be reset. Save the baseline before resetting statistics.
Also, do not assume queryid values are stable across different PostgreSQL major versions, builds, or environments. Use normalized SQL text, application query names, and your own workload identifiers to match statements between versions.
Comparing Execution Plans
Once a query has been identified, compare its execution plans from PostgreSQL 18 and PostgreSQL 19.
Consider the following example from a reporting application:
SELECT
c.customer_name,
COUNT(o.order_id) AS total_orders,
SUM(o.total_amount) AS total_sales
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id
WHERE o.order_date >= DATE '2026-01-01'
GROUP BY c.customer_name;Suppose the earlier execution plan used a hash join, but PostgreSQL 19 chooses a different join strategy.
The following areas should be reviewed:
Scan Operations
Check whether the query uses a sequential scan, index scan, index-only scan, or bitmap heap scan.
A sequential scan is not necessarily inefficient. It can be the best option when a query needs a large portion of a table.
However, if a selective query unexpectedly stops using an appropriate index, investigate table statistics, index definitions, and estimated row counts.
Join Operations
Compare the join algorithms used by both versions.
Common join operations include:
- Nested Loop: Often useful when one input is small and the other can be accessed efficiently through an index.
- Hash Join: Builds a hash table from one input and uses it to match rows from another input.
- Merge Join: Uses sorted inputs to match rows efficiently.
A different join algorithm can change memory usage, disk activity, and execution time.
Estimated and Actual Rows
One of the most useful checks is comparing estimated rows with actual rows.
For example, a plan might estimate that a filter returns 100 rows but actually return 50,000 rows.
Large differences can influence the planner's choice of join method and scan strategy.
When estimates are inaccurate, inspect the table statistics and consider running:
ANALYZE orders;For columns with uneven data distribution, increasing the statistics target may help:
ALTER TABLE orders
ALTER COLUMN customer_id
SET STATISTICS 500;
ANALYZE orders;A higher statistics target can improve estimates, but it also increases the amount of statistics data collected. Apply it selectively to columns where better estimates are needed.
Using PostgreSQL 19's IO Information
PostgreSQL 19 adds an IO option to EXPLAIN ANALYZE.
It reports additional information about I/O activity performed by supported scan nodes, including prefetch queue information and issued I/O requests.
For example:
EXPLAIN (
ANALYZE,
BUFFERS,
IO,
SETTINGS
)
SELECT
order_id,
customer_id,
total_amount
FROM orders
WHERE order_date >= CURRENT_DATE - INTERVAL '30 days';The IO option is useful when a query's performance changes because of disk access behavior.
For example, a query may have a similar execution plan after an upgrade but perform differently because the number of I/O requests, prefetch behavior, or wait activity has changed.
The IO option requires ANALYZE because the information comes from actual execution.
Use it alongside BUFFERS rather than treating either output as a complete performance measurement.
Using pg_plan_advice to Investigate Different Plans
One of the important PostgreSQL 19 additions is pg_plan_advice.
This extension allows developers to inspect planner decisions and provide advice that constrains selected planning choices.
First, load the extension in the current session:
LOAD 'pg_plan_advice';Then inspect the plan with PLAN_ADVICE:
EXPLAIN (
COSTS OFF,
PLAN_ADVICE
)
SELECT *
FROM orders o
JOIN customers c
ON o.customer_id = c.customer_id
WHERE c.customer_id = 1050;PostgreSQL displays the selected execution plan along with generated plan advice.
For example, the advice may describe the join order, join method, and scan methods selected by the planner.
A developer can use the generated advice as a starting point for experimentation.
Consider the following example:
SET pg_plan_advice.advice =
'JOIN_ORDER(o c)';This instructs the planner to use the specified join order when a matching plan can be produced.
The important point is that pg_plan_advice constrains planner choices rather than replacing the planner with an entirely separate execution strategy.
It should be used carefully. Forcing a particular plan can improve one workload while making another workload slower, especially when table sizes and data distributions change.
Start by using EXPLAIN to understand the existing plan. Apply advice only after identifying a specific planning problem and measuring the result.
Automatically Applying Advice With pg_stash_advice
PostgreSQL 19 also provides pg_stash_advice, which stores plan advice and applies it automatically to queries using their query identifiers.
This is useful when a team identifies a query that consistently receives a poor plan and wants to apply reviewed advice without modifying application SQL.
The extension must be loaded in the relevant sessions. It can be configured through shared_preload_libraries, and the advice stash can be managed through SQL functions.
After installing the extension, create an advice stash:
CREATE EXTENSION pg_stash_advice;
SELECT pg_create_advice_stash('production_advice');Suppose the query identifier and reviewed advice string have already been collected.
The team can store the advice:
SELECT pg_set_stashed_advice(
'production_advice',
123456789012345678,
'JOIN_ORDER(o c)'
);The example query identifier is illustrative. Use the actual identifier reported by PostgreSQL for the target statement.
Next, configure the session to use the stash:
SET pg_stash_advice.stash_name = 'production_advice';When a matching query is planned, PostgreSQL applies the stored advice.
For automatic use across sessions, the extension must be loaded appropriately, and the stash name should be configured at the required database, role, or session level.
Advice is applied when a query is planned. Existing cached plans are not automatically replaced when the stash changes. Prepared statements and other cached plans may need to be replanned before updated advice takes effect.
Because plan advice can become unsuitable as data changes, maintain it as a reviewed performance intervention rather than a permanent replacement for accurate statistics and planner decisions.
Best Practices for PostgreSQL 19 Upgrade Testing
A reliable upgrade process should include performance testing before production deployment.
The following practices help identify plan regressions early:
- Capture frequently executed SQL statements from the existing PostgreSQL environment.
- Save execution plans using EXPLAIN with JSON output.
- Record execution time, row counts, buffer activity, and relevant configuration settings.
- Restore representative data into the PostgreSQL 19 test environment.
- Run ANALYZE after loading or changing substantial amounts of data.
- Execute the same workload with comparable parameter values.
- Compare plan nodes, estimated rows, actual rows, and execution behavior.
- Investigate changed plans before applying planner advice.
- Test any plan advice against realistic data and workload variations.
- Monitor query performance after production deployment.
Avoid changing planner configuration globally just because one query receives a different plan. A setting that improves one query can negatively affect other queries.
Summary
A PostgreSQL major-version upgrade can change query execution plans because the planner receives new optimization capabilities and may make different decisions based on statistics, data distribution, and configuration.
PostgreSQL 19 provides several useful tools for investigating these changes. EXPLAIN ANALYZE helps compare actual execution behavior, pg_stat_statements identifies expensive queries, and the new IO option provides additional visibility into disk activity.
The pg_plan_advice extension allows developers to inspect and constrain selected planner decisions, while pg_stash_advice can automatically apply reviewed advice using query identifiers.
The best approach is to capture a performance baseline before upgrading, compare representative workloads after the upgrade, and investigate the reason behind every significant regression. Use plan advice only when measurements demonstrate that the planner consistently makes a poor choice. This keeps query optimization controlled and helps applications benefit from PostgreSQL 19 without introducing unnecessary performance risks.


Join the conversation! Your thoughts help the community grow.