Upgrading PostgreSQL can improve database performance, provide new capabilities, and make applications more reliable. However, an upgrade can also introduce performance regressions that are difficult to identify immediately. Some queries may become slower even though their SQL statements, indexes, and application code have not changed.
This often happens because PostgreSQL's query planner makes decisions based on table statistics, data distribution, available indexes, configuration settings, and estimated execution costs. A newer PostgreSQL version may choose a different execution plan for the same query. Sometimes the new plan is better, but in other situations it can increase execution time, database reads, CPU usage, or memory consumption.
The challenge is that an application may execute hundreds or thousands of different SQL statements. Checking every query manually is not practical, especially in a production environment.
PostgreSQL provides tools such as pg_stat_statements, EXPLAIN ANALYZE, and auto_explain that help identify slow queries and investigate their execution behavior. By collecting performance information before and after an upgrade, developers can narrow down the queries responsible for regressions and determine whether the problem comes from statistics, indexing, query structure, or planner decisions.
This article explains a practical approach to finding PostgreSQL queries that became slower after a major-version upgrade.
Why Queries Become Slower After an Upgrade
A PostgreSQL upgrade does not automatically make every query faster. The optimizer may change its decisions because the new version includes planner improvements, different cost calculations, or changes in execution behavior.
Consider an application that retrieves recent orders for a customer.
SELECT
id,
customer_id,
order_date,
total_amount
FROM orders
WHERE customer_id = 5001
ORDER BY order_date DESC
LIMIT 20;
Suppose the application previously executed this query in a few milliseconds. After upgrading PostgreSQL, the same query takes considerably longer.
Several reasons could explain the difference.
- The planner selects a sequential scan instead of an index scan.
- Estimated row counts are significantly different from actual row counts.
- Table statistics are outdated or insufficient.
- An index is missing, invalid, or no longer useful for the query.
- A join changes from a hash join to a nested loop.
- A prepared statement uses a generic plan that performs poorly for certain parameter values.
- Configuration settings affecting memory, parallelism, or query planning have changed.
It is important to distinguish an upgrade-related regression from normal workload variation. A query may become slower because the database now contains more records, the application sends different parameter values, or the underlying infrastructure has changed.
A useful investigation compares the same query under similar data, configuration, and workload conditions.
Establishing a Performance Baseline Before the Upgrade
The easiest way to identify a regression is to collect performance information before upgrading.
The pg_stat_statements extension is one of the most useful tools for this purpose. It tracks SQL execution statistics and groups similar statements using query identifiers.
First, configure the extension in postgresql.conf.
shared_preload_libraries = 'pg_stat_statements'
compute_query_id = auto
The shared_preload_libraries setting requires a PostgreSQL restart when it is changed.
Then create the extension in the application database.
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
You can identify expensive queries using the following statement.
SELECT
queryid,
calls,
total_exec_time,
mean_exec_time,
max_exec_time,
rows,
query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
This query identifies statements that consume significant total execution time.
However, total execution time alone does not tell the complete story. A query executed once may take several seconds, while another query executed thousands of times may take only a few milliseconds per execution.
Both can be important for different reasons.
For a more useful baseline, collect the following information:
- Number of executions.
- Total execution time.
- Mean execution time.
- Maximum execution time.
- Rows returned.
- Planning time, when planning statistics are enabled.
- Query text and execution plan.
Save this information before the upgrade. It provides a reference for identifying queries that deserve investigation afterward.
Finding Slow Queries After the Upgrade
After upgrading PostgreSQL, allow the application to execute its normal workload before comparing performance statistics.
Do not immediately compare an almost empty database with a fully loaded production environment. The workload should be reasonably representative.
Run the following query on the upgraded database.
SELECT
queryid,
calls,
total_exec_time,
mean_exec_time,
max_exec_time,
rows,
query
FROM pg_stat_statements
ORDER BY mean_exec_time DESC
LIMIT 20;
This identifies statements with high average execution time.
You can also find queries consuming the most total database execution time.
SELECT
queryid,
calls,
total_exec_time,
mean_exec_time,
rows,
query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
Compare the results with the baseline collected before the upgrade.
There is one important consideration when comparing query identifiers across major versions. Query identifiers are internal hashes used to group query structures. They should not be treated as permanent identifiers that are guaranteed to remain identical across different PostgreSQL versions.
For a reliable comparison, use the normalized SQL structure, query text, application context, and execution characteristics together. Also consider that pg_stat_statements combines queries with different literal values into a representative normalized statement.
If the application uses parameterized queries, the same normalized statement may execute with very different parameter values. Averages can hide slow executions for particular customers or data ranges.
Comparing Execution Plans With EXPLAIN ANALYZE
Once a slow query has been identified, the next step is to examine its execution plan.
PostgreSQL provides EXPLAIN to show the plan selected by the planner.
EXPLAIN
SELECT
id,
customer_id,
order_date,
total_amount
FROM orders
WHERE customer_id = 5001
ORDER BY order_date DESC
LIMIT 20;
This shows the planned operations, including table scans, index scans, joins, and sorting.
To understand what actually happened during execution, 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;
The output includes estimated and actual row counts, execution time, and buffer activity.
Consider an example where PostgreSQL estimates that a query will return 15 rows but actually processes 40,000 rows.
That difference can affect the planner's choice of execution strategy. A plan that appears inexpensive based on incorrect estimates may perform poorly when executed against real data.
Compare these details with the execution plan collected before the upgrade:
Plan information | What to investigate |
|---|
Scan type | Did an index scan change to a sequential scan? |
Join type | Did a hash join change to a nested loop? |
Estimated rows | Are planner estimates significantly different? |
Actual rows | Is the query processing more data than expected? |
Buffers | Are there more physical reads or buffer accesses? |
Sort operations | Is an additional or expensive sort happening? |
Execution time | Which plan nodes consume the most time? |
Do not assume that a sequential scan or a different join type is automatically a problem. The correct plan depends on the amount of data being processed and the available resources.
Also remember that EXPLAIN ANALYZE actually executes the statement. For queries that modify data, use a transaction and roll it back when the changes must not be retained.
Checking Statistics Before Changing Indexes
One of the first things to investigate after an upgrade is whether the planner has useful statistics.
PostgreSQL uses statistics collected by ANALYZE to estimate how many rows match query conditions. These estimates help determine which execution plan is likely to be efficient.
After restoring data or completing an upgrade, run ANALYZE.
ANALYZE;
For a large production database, analyzing individual tables may be more practical.
ANALYZE orders;
ANALYZE customers;
ANALYZE order_items;
If a particular column is important to query performance, you can inspect its statistics through pg_stats.
SELECT
tablename,
attname,
null_frac,
n_distinct,
most_common_vals,
most_common_freqs
FROM pg_stats
WHERE tablename = 'orders';
This helps identify whether the planner has useful information about the values stored in a column.
Using Extended Statistics for Correlated Columns
Sometimes a query filters on multiple columns whose values are related.
For example, an order table may contain status and region columns. Certain statuses may be much more common in particular regions.
PostgreSQL normally estimates individual conditions using column statistics. When conditions are correlated, assuming that they are independent can produce inaccurate estimates.
Extended statistics can help capture relationships between columns.
CREATE STATISTICS orders_status_region_stats
(dependencies, mcv)
ON status, region
FROM orders;
Collect the statistics after creating the object.
ANALYZE orders;
The planner can then use the additional information when estimating queries involving these columns.
Do not create extended statistics for every possible column combination. Identify queries with inaccurate row estimates and select the columns that are relevant to those conditions.
Investigating Index and Query Changes
If statistics are current but a query remains slow, inspect the indexes used by the query.
Start by checking the existing indexes.
SELECT
indexname,
indexdef
FROM pg_indexes
WHERE schemaname = 'public'
AND tablename = 'orders';
Suppose the application frequently filters by customer_id and sorts by order_date.
A composite index may support this access pattern.
CREATE INDEX idx_orders_customer_order_date
ON orders (customer_id, order_date DESC);
Before creating a new index, check whether an existing index already supports the query. Additional indexes increase storage usage and add overhead to INSERT, UPDATE, and DELETE operations.
Also inspect whether the query has changed indirectly through application code.
For example, a query that previously filtered by a specific customer may now use a function on the indexed column.
SELECT *
FROM orders
WHERE LOWER(customer_code) = LOWER('CUST1001');
A normal index on customer_code may not support this expression efficiently. An expression index could be more appropriate.
CREATE INDEX idx_orders_customer_code_lower
ON orders (LOWER(customer_code));
The right solution depends on the query's actual execution plan and the application's access patterns.
Checking Prepared Statements and Parameter-Sensitive Queries
Applications commonly use parameterized SQL statements to improve security and support efficient database access.
However, prepared statements can introduce another performance consideration.
PostgreSQL may use a custom plan based on the actual parameter values or a generic plan that does not depend on individual parameter values.
A generic plan can work well when parameter values have similar selectivity. It may perform poorly when some values match only a few rows while others match a large portion of a table.
You can inspect a prepared statement using EXPLAIN EXECUTE.
PREPARE customer_orders(bigint) AS
SELECT
id,
order_date,
total_amount
FROM orders
WHERE customer_id = $1
ORDER BY order_date DESC;
Then examine its plan for different parameter values.
EXPLAIN ANALYZE
EXECUTE customer_orders(5001);
EXPLAIN ANALYZE
EXECUTE customer_orders(9000);
If execution behavior differs significantly, investigate whether the statement is receiving a suitable plan for the actual parameter distribution.
PostgreSQL also provides the plan_cache_mode setting for diagnostic and operational control.
SET plan_cache_mode = force_custom_plan;
This setting can help determine whether custom planning improves a problematic prepared statement. It should not be applied globally without measurement because generating a new plan for every execution increases planning work.
For a controlled comparison, test the alternatives in separate sessions and measure both planning and execution costs.
Monitoring Regressions With pg_stat_statements
A one-time query comparison is useful, but production databases need continuous monitoring.
The pg_stat_statements view provides information about query execution over time.
You can enable planning statistics with the following setting.
pg_stat_statements.track_planning = on
This requires the extension to be loaded and the configuration to be applied according to its setting requirements. Planning statistics can add overhead, particularly when many concurrent sessions execute identical statements, so measure the impact before enabling them across a busy production workload.
After enabling planning statistics, inspect queries with high planning and execution costs.
SELECT
queryid,
calls,
mean_plan_time,
mean_exec_time,
total_exec_time,
query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
This helps distinguish queries that spend significant time generating execution plans from those that spend most of their time executing them.
For longer investigations, remember that pg_stat_statements statistics are cumulative until they are reset or the relevant entries are removed. Record the observation period when comparing values. Comparing two cumulative totals collected over different periods can produce misleading conclusions.
Capturing Slow Queries With auto_explain
Sometimes a query becomes slow only under a particular production workload. Running it manually with EXPLAIN ANALYZE may not reproduce the same conditions.
The auto_explain module can capture execution plans for statements that exceed a configured duration.
Add the module to shared_preload_libraries.
shared_preload_libraries = 'pg_stat_statements,auto_explain'
Configure a logging threshold.
auto_explain.log_min_duration = '500ms'
auto_explain.log_analyze = on
auto_explain.log_buffers = on
auto_explain.log_timing = off
These settings are examples. Choose a threshold based on the application's normal query response times and logging capacity.
The log_analyze option adds actual execution information to captured plans. Disabling per-node timing can reduce instrumentation overhead while still providing useful row and buffer information.
Review the PostgreSQL logs to identify statements that cross the configured threshold.
Be careful when enabling detailed plan logging in production. Logs can grow quickly, and query text or parameter-related information may contain sensitive application data. Apply appropriate access controls and retention policies.
A Practical Performance Regression Workflow
A consistent investigation process makes upgrade-related performance problems easier to diagnose.
- Collect query statistics and execution plans before upgrading.
- Upgrade PostgreSQL and verify the application connection and database configuration.
- Run ANALYZE after the migration so the planner has current statistics.
- Allow representative application traffic to execute against the upgraded database.
- Compare query execution statistics with the baseline, using normalized SQL and application context rather than relying only on query identifiers.
- Run EXPLAIN ANALYZE on the queries that show meaningful regressions.
- Check row estimates, buffer activity, indexes, joins, and prepared statement behavior.
- Apply targeted fixes and measure their impact under realistic workload conditions.
- Continue monitoring after deployment to confirm that the improvement remains consistent.
Keep the original performance measurements and the results of each investigation. This makes it easier to distinguish a genuine improvement from a temporary change in workload or cache state.
Common Mistakes to Avoid
One common mistake is comparing query execution times without considering the number of executions. A query that runs thousands of times may have a greater impact on application performance than a query that runs slowly only once.
Another mistake is immediately creating new indexes whenever a query becomes slower. The actual problem may be outdated statistics, an inaccurate row estimate, or a change in prepared statement planning.
Developers should also avoid comparing query identifiers as if they were guaranteed to remain unchanged across PostgreSQL major versions. Use normalized SQL and execution characteristics to identify corresponding statements.
Do not rely exclusively on average execution time. Averages can hide parameter-sensitive problems where some executions are fast and others are extremely slow.
Finally, avoid treating EXPLAIN ANALYZE timings as exact production measurements. Instrumentation adds overhead, and the result can vary depending on cache state, concurrency, and available resources.
Summary
Finding queries that became slower after a PostgreSQL upgrade requires a comparison of actual database behavior, not just a review of SQL statements.
The most effective approach is to collect a performance baseline before the upgrade, identify expensive statements through pg_stat_statements, and investigate suspicious queries using EXPLAIN ANALYZE. Updated statistics, extended statistics, index analysis, prepared statement behavior, and execution-plan logging can help identify the underlying cause.
For production applications, use representative workloads and compare results over meaningful observation periods. Avoid making broad planner changes or creating indexes without evidence.
A successful PostgreSQL upgrade should be validated at the query level. By combining baseline measurements, execution-plan analysis, and continuous monitoring, development teams can detect performance regressions early and keep database-backed applications responsive after a major-version upgrade.
Join the conversation! Your thoughts help the community grow.