Upgrading PostgreSQL to a newer major version can improve database performance, introduce useful features, and provide better optimization for existing workloads. However, an upgrade does not guarantee that every query will continue using the same execution plan.
The PostgreSQL query planner evaluates different execution strategies and selects a plan based on available statistics, indexes, configuration settings, and estimated execution costs. A query that previously used an index scan may start using a sequential scan after an upgrade. A join that previously performed well with a hash join may switch to a nested loop. These changes can affect application response times even when the SQL statements remain unchanged.
This becomes particularly important for applications that execute thousands of queries every minute. A small performance regression in one frequently executed query can increase database CPU usage, consume more connections, and affect API response times.
PostgreSQL 19 introduces pg_plan_advice and pg_stash_advice, providing new ways to inspect, control, and preserve selected query planner decisions. Instead of blindly accepting every new execution plan or permanently disabling planner optimizations, developers can apply targeted advice to queries that have demonstrated performance problems.
This article explains how query plans can change after an upgrade, how PostgreSQL 19 plan advice works, and how to use these capabilities to manage query performance in production applications.
Why Query Plans Change After a PostgreSQL Upgrade
PostgreSQL does not execute every SQL statement using a fixed strategy. The query planner evaluates possible execution plans and estimates their costs before selecting one.
Consider an application that retrieves customer orders using a customer identifier.
SELECT
id,
customer_id,
order_date,
total_amount
FROM orders
WHERE customer_id = 5001
ORDER BY order_date DESC
LIMIT 20;The application may have an index on customer_id and order_date.
CREATE INDEX idx_orders_customer_date
ON orders (customer_id, order_date DESC);The planner might choose an index scan because the query retrieves only a small number of rows.
However, after an upgrade, the planner may choose a different execution strategy because its costing logic, available statistics, configuration, or understanding of the query has changed.
Several factors can influence this decision:
Changes in query planner optimizations.
Different estimates of the number of matching rows.
Updated table and column statistics.
Changes in PostgreSQL configuration parameters.
Changes in the distribution of application data.
New optimizer capabilities in the upgraded version.
Different execution characteristics of the database infrastructure.
A major upgrade does not necessarily change every query plan. Many queries may continue using the same strategy or become faster. The important point is that developers should validate critical queries instead of assuming that an unchanged SQL statement will always produce an unchanged plan.
Understanding EXPLAIN Before Stabilizing Query Plans
The first step in investigating a query performance regression is to examine its execution plan.
PostgreSQL provides the EXPLAIN command for this purpose.
EXPLAIN
SELECT
id,
customer_id,
order_date,
total_amount
FROM orders
WHERE customer_id = 5001
ORDER BY order_date DESC
LIMIT 20;The output describes the operations PostgreSQL plans to perform.
For example, a plan may contain an Index Scan, while another plan may contain a Sequential Scan followed by a Sort operation.
To understand actual execution behavior, use EXPLAIN ANALYZE.
EXPLAIN (ANALYZE, BUFFERS)
SELECT
id,
customer_id,
order_date,
total_amount
FROM orders
WHERE customer_id = 5001
ORDER BY order_date DESC
LIMIT 20;This executes the query and reports actual execution details, including:
Estimated and actual row counts.
Execution time.
Planning time.
Shared buffer hits and reads.
Operations performed by individual plan nodes.
Pay particular attention to differences between estimated rows and actual rows. If PostgreSQL estimates that a query will return 10 rows but it actually returns 50,000, the planner may have selected an inefficient strategy because its assumptions were incorrect.
EXPLAIN ANALYZE executes the statement. For SELECT queries, it performs the normal read operation. For statements that modify data, such as UPDATE or DELETE, use a transaction and roll it back when testing effects must not be retained.
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE orders
SET total_amount = total_amount + 10
WHERE customer_id = 5001;
ROLLBACK;This allows developers to inspect the execution while preventing the changes from being committed.
Collecting Query Plan Information Before an Upgrade
A reliable upgrade process starts before the migration.
Developers should identify the queries that are important to application performance and capture their existing execution plans.
For example, an e-commerce application may have critical queries for:
Customer order history.
Product availability.
Payment transaction lookup.
Inventory updates.
Dashboard reporting.
Background job processing.
Not every SQL statement needs to be documented individually. Focus on frequently executed queries and queries that consume significant database resources.
The pg_stat_statements extension is useful for identifying these queries.
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;You can then inspect frequently executed statements.
SELECT
queryid,
calls,
total_exec_time,
mean_exec_time,
rows,
query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;The query identifier helps identify normalized query patterns, while execution statistics show which statements deserve further investigation.
Capture EXPLAIN output for important queries before the upgrade and compare it with the plans generated by the upgraded database.
The comparison should include more than the selected scan or join type. Estimated row counts, actual row counts, buffer usage, planning time, and execution time all provide useful information.
Introducing pg_plan_advice in PostgreSQL 19
PostgreSQL 19 introduces the pg_plan_advice module, which allows developers and database administrators to describe important query planner decisions using a dedicated advice language.
Instead of directly replacing the PostgreSQL optimizer, the module constrains some of the planner's available choices.
This distinction is important. PostgreSQL continues to generate a valid execution plan, but selected decisions can be influenced by the advice provided.
The module can help with decisions such as:
Join order.
Join methods.
Table scan methods.
Parallel query behavior.
Index selection for specific relations.
For example, suppose a query joins an orders table with a customers table.
SELECT
o.id,
o.total_amount,
c.customer_name
FROM orders o
JOIN customers c
ON c.id = o.customer_id
WHERE o.customer_id = 5001;PostgreSQL may choose a hash join or a nested loop depending on the estimated costs and available indexes.
With pg_plan_advice, developers can inspect the planner's current decisions and generate an advice string.
Loading pg_plan_advice
The module must be loaded before its functionality can be used.
For system-wide availability, add it to shared_preload_libraries in the PostgreSQL configuration.
shared_preload_libraries = 'pg_stat_statements,pg_plan_advice'Changing shared_preload_libraries requires a PostgreSQL server restart.
For testing, the module can also be loaded into an individual session using LOAD.
LOAD 'pg_plan_advice';Once loaded, EXPLAIN supports the PLAN_ADVICE option.
EXPLAIN (COSTS OFF, PLAN_ADVICE)
SELECT
o.id,
o.total_amount,
c.customer_name
FROM orders o
JOIN customers c
ON c.id = o.customer_id
WHERE o.customer_id = 5001;The output includes the execution plan and a generated advice string.
For example, the generated advice may look like this:
JOIN_ORDER(o c)
HASH_JOIN(c)
SEQ_SCAN(o c)
NO_GATHER(o c)These instructions describe important decisions made by the planner.
JOIN_ORDER(o c) specifies that orders should be the driving relation, followed by customers.
HASH_JOIN(c) specifies that customers should appear on the inner side of a hash join.
SEQ_SCAN(o c) specifies sequential scans for both relations.
NO_GATHER(o c) prevents the specified relations from appearing beneath a Gather or Gather Merge node.
The generated advice is based on the actual query and plan. Developers should inspect the generated output rather than copying advice from an unrelated example.
Applying Plan Advice to a Query
After reviewing the generated advice, developers can apply selected instructions to a query.
For example, suppose testing shows that the join order is important, but the planner should remain free to select the join method and scan strategy.
The application can use only the join-order instruction.
SET pg_plan_advice.advice = 'JOIN_ORDER(o c)';Execute the query again with EXPLAIN.
EXPLAIN (COSTS OFF)
SELECT
o.id,
o.total_amount,
c.customer_name
FROM orders o
JOIN customers c
ON c.id = o.customer_id
WHERE o.customer_id = 5001;The output identifies supplied advice and indicates whether it matched the query.
A successful match is useful because it confirms that PostgreSQL recognized the specified relations and applied the requested constraint.
Developers should avoid applying every instruction from a generated advice string automatically. A query may need only one stable decision, such as join order. Keeping advice limited to the necessary decisions allows the optimizer to continue adapting other parts of the plan as the data changes.
There is also an important limitation: plan advice cannot force every theoretically possible execution strategy. PostgreSQL still considers whether a plan is semantically valid and whether the requested operations are available. Incorrect or impossible advice may result in disabled plan nodes or an execution plan that is worse than the original.
Using pg_stash_advice to Apply Advice Automatically
Setting pg_plan_advice.advice manually is useful during testing, but it is not convenient for applications that execute the same queries through multiple connections.
PostgreSQL 19 also introduces pg_stash_advice.
This module allows developers to store advice strings in a shared-memory advice stash and associate them with query identifiers.
When a session plans a query whose identifier appears in the configured stash, PostgreSQL automatically applies the corresponding advice.
This makes it possible to manage selected query plans centrally instead of requiring every application connection to execute a separate SET command.
Creating an Advice Stash
First, create the extension in the database.
CREATE EXTENSION pg_stash_advice;Then create an advice stash.
SELECT pg_create_advice_stash('production_queries');The stash provides a named collection of query identifiers and their associated advice strings.
Finding the Query Identifier
The query identifier can be obtained through EXPLAIN with the VERBOSE option.
EXPLAIN (VERBOSE, COSTS OFF, PLAN_ADVICE)
SELECT
o.id,
o.total_amount,
c.customer_name
FROM orders o
JOIN customers c
ON c.id = o.customer_id
WHERE o.customer_id = 5001;The output includes the query identifier and generated plan advice.
The query identifier can also be obtained from pg_stat_statements when query ID calculation is enabled.
SELECT
queryid,
calls,
mean_exec_time,
query
FROM pg_stat_statements
WHERE query ILIKE '%FROM orders%';The query identifier and advice string should be captured from the actual statement being managed.
Storing Advice for a Query
After identifying the correct query ID and advice, store them in the advice stash.
SELECT pg_set_stashed_advice(
'production_queries',
1234567890123456789,
'JOIN_ORDER(o c)'
);The numeric query identifier in this example is illustrative. Replace it with the actual identifier returned by PostgreSQL.
The function associates the advice string with that query ID. If an entry already exists for the same query ID in the stash, the existing entry is replaced.
Next, configure PostgreSQL to use the stash.
SET pg_stash_advice.stash_name = 'production_queries';For application-wide or database-wide configuration, administrators can use ALTER DATABASE or ALTER ROLE rather than setting the value separately in every session.
For example:
ALTER DATABASE application_db
SET pg_stash_advice.stash_name = 'production_queries';New sessions connected to that database will use the configured stash.
The module must also be loaded in the sessions where automatic advice application is required. For a production deployment, configure pg_stash_advice through shared_preload_libraries and restart the server as required.
The advice stash is stored in dynamically allocated shared memory. PostgreSQL can also persist its contents to disk when persistence is enabled.
Managing Advice After Deployment
Plan advice should be treated as a managed database configuration rather than a permanent fix that never needs review.
PostgreSQL provides functions to inspect existing advice stashes.
SELECT *
FROM pg_get_advice_stashes();To inspect the contents of a particular stash:
SELECT *
FROM pg_get_advice_stash_contents(
'production_queries'
);If an advice entry is no longer required, remove it by passing NULL as the advice string.
SELECT pg_set_stashed_advice(
'production_queries',
1234567890123456789,
NULL
);The example query identifier should again be replaced with the actual identifier.
To remove an entire stash, use:
SELECT pg_drop_advice_stash(
'production_queries'
);This is useful when a query has been optimized, the underlying data distribution has changed, or a previous plan constraint is no longer beneficial.
One important detail is that advice changes affect queries when they are planned. Existing cached plans are not automatically rewritten just because an advice entry changes. Developers should account for prepared statements and plan caching when validating changes.
Integrating Plan Advice With a .NET Application
Most .NET applications connect to PostgreSQL using Npgsql. The application does not need to implement its own query planner or manually generate advice strings.
The database administrator can manage advice centrally, while the application continues executing its normal parameterized SQL statements.
For example, a repository method can execute the same query as before:
using Npgsql;
public class OrderRepository
{
private readonly NpgsqlDataSource _dataSource;
public OrderRepository(NpgsqlDataSource dataSource)
{
_dataSource = dataSource;
}
public async Task<List<Order>> GetCustomerOrdersAsync(
long customerId,
CancellationToken cancellationToken = default)
{
const string sql = """
SELECT
id,
customer_id,
order_date,
total_amount
FROM orders
WHERE customer_id = @customerId
ORDER BY order_date DESC
LIMIT 20;
""";
var orders = new List<Order>();
await using var connection =
await _dataSource.OpenConnectionAsync(
cancellationToken);
await using var command =
new NpgsqlCommand(sql, connection);
command.Parameters.AddWithValue(
"customerId",
customerId);
await using var reader =
await command.ExecuteReaderAsync(
cancellationToken);
while (await reader.ReadAsync(cancellationToken))
{
orders.Add(new Order
{
Id = reader.GetInt64(0),
CustomerId = reader.GetInt64(1),
OrderDate =
reader.GetFieldValue<DateTimeOffset>(2),
TotalAmount = reader.GetDecimal(3)
});
}
return orders;
}
}When the query is planned, PostgreSQL checks the configured advice stash and applies matching advice automatically.
This keeps query-plan management separate from application business logic.
However, developers should test this behavior with the actual Npgsql connection configuration, prepared statement usage, connection pooling, and database roles used in production. Plan advice is applied during planning, so cached plans and session configuration can affect when a change becomes visible.
Understanding the Risks of Stabilizing Query Plans
Keeping a query plan stable sounds beneficial, but forcing a planner decision can become a problem when application data changes.
Imagine that an orders table contains one million records when the original plan advice is created. The query performs well with a particular join order.
After several months, the table grows to fifty million records and the distribution of customer orders changes significantly.
The original plan may no longer be efficient.
Without plan advice, PostgreSQL can reconsider its execution strategy based on the updated statistics and current data distribution. If the advice continues constraining the planner, the database may retain a strategy that is no longer appropriate.
There are several risks to consider:
An old join order may become inefficient.
An index scan may perform worse than a sequential scan for a larger result set.
A previously useful parallelism restriction may reduce performance.
Changes in table statistics may make old assumptions incorrect.
Advice that no longer matches the query structure may not be applied as expected.
Plan advice should therefore be reviewed whenever application workloads, schema definitions, indexes, or data distributions change significantly.
A Practical Upgrade Strategy for Production Databases
A PostgreSQL major-version upgrade should include a query-plan validation process.
A practical workflow can be organized into the following stages.
Before the Upgrade
Identify the application's most important queries using pg_stat_statements.
Capture their query identifiers, execution statistics, and EXPLAIN output.
Record important database settings, index definitions, and table statistics. Also identify queries that already have performance problems so that they are not incorrectly treated as upgrade regressions.
During Upgrade Testing
Restore a representative copy of production data into the upgraded PostgreSQL environment.
Run ANALYZE after the data migration so that the new planner has current statistics.
Execute important queries with EXPLAIN ANALYZE and compare their behavior with the previous version.
Pay attention to changes in actual execution time, row estimates, buffer activity, scan methods, and join strategies.
Before Applying Advice
First investigate whether the problem is caused by outdated statistics, missing indexes, unsuitable query structure, or incorrect configuration.
Do not use plan advice to hide a problem that can be fixed more directly.
If a particular planner decision is still consistently better under representative production conditions, create targeted advice for that query.
After Deployment
Monitor query performance through pg_stat_statements and application-level metrics.
Review advice entries periodically and remove constraints that no longer provide a measurable benefit.
Keep a record of why each advice entry was introduced, which query it affects, and what performance issue it addresses.
Common Mistakes to Avoid
One common mistake is assuming that a query must use an index scan to be efficient. A sequential scan can be the correct choice when a query needs a large portion of a table.
Another mistake is copying an entire generated advice string into production without understanding its individual instructions. A query may need only a join-order restriction, while its scan and parallelism decisions should remain under the planner's control.
Developers should also avoid applying the same advice to every query in an application. Advice should be associated with specific query identifiers and justified by actual execution evidence.
Do not forget that query statistics and plan advice are different things. Updated statistics help the planner make better decisions, while advice constrains selected decisions. Correct statistics should normally be the first priority.
Finally, do not assume that changing an advice entry immediately changes an already cached execution plan. Test the behavior with the same connection and prepared statement patterns used by the application.
Summary
PostgreSQL query plans can change after a major-version upgrade because the planner evaluates execution strategies using statistics, configuration, data distribution, and optimizer capabilities. These changes can improve many queries, but they can also introduce performance regressions in important application workflows.
PostgreSQL 19 introduces pg_plan_advice for describing and controlling selected planner decisions. The companion pg_stash_advice module allows developers to associate advice strings with query identifiers and apply them automatically when queries are planned.
For .NET applications using Npgsql, these capabilities can be managed at the database level without changing ordinary repository methods or business logic.
The most important principle is to stabilize only the query plans that genuinely need it. Start with EXPLAIN ANALYZE, compare behavior before and after the upgrade, correct statistics and indexing problems, and use targeted advice only when there is clear evidence that a planner decision should be constrained.
A successful PostgreSQL upgrade should not depend on forcing every query to use its old execution plan. It should preserve reliable application performance while allowing the query planner to take advantage of improvements in the newer database version.


Join the conversation! Your thoughts help the community grow.