Upgrading PostgreSQL to a new major version can improve database performance, introduce useful features, and provide better query optimization. However, an upgrade does not guarantee that every application query will become faster.
PostgreSQL uses a query planner to decide how SQL statements should execute. It evaluates available indexes, table statistics, join methods, sorting operations, and estimated execution costs before selecting an execution plan.
A new PostgreSQL version may choose a different plan for the same SQL statement. Sometimes the new plan is more efficient. In other situations, a query that previously completed in milliseconds may take considerably longer because the planner selects a less suitable execution strategy.
PostgreSQL 19 includes several optimizer improvements, including changes to anti-join processing, aggregation, and join planning. These changes can improve many workloads, but their impact depends on the application's queries and data distribution.
In this article, we will explore how to capture existing query plans, compare them with PostgreSQL 19 execution plans, identify performance regressions, and prepare a database upgrade without unexpected query performance problems.
Why Query Plan Testing Matters Before an Upgrade
Consider an application that retrieves customer orders using a JOIN:
SELECT
c.customer_id,
c.customer_name,
o.order_id,
o.order_date,
o.total_amount
FROM customers c
JOIN orders o
ON c.customer_id = o.customer_id
WHERE c.customer_id = 1001
ORDER BY o.order_date DESC;PostgreSQL can execute this query using different strategies, depending on the available indexes, statistics, table sizes, and estimated costs.
For example, it might choose:
- An index scan to retrieve a specific customer.
- A sequential scan when reading a large portion of a table.
- A nested loop join for a small result set.
- A hash join when joining larger datasets.
- A sort operation to produce the requested order.
The planner estimates the cost of these alternatives and selects a plan.
After upgrading, PostgreSQL may choose a different join method or access path because its optimizer logic, statistics, or configuration has changed.
This is why comparing only query execution time before and after an upgrade is not enough. Developers should also understand which execution plan PostgreSQL selected and why.
Capture Existing Query Plans Before Upgrading
The first step is to identify important application queries and capture their current execution plans.
PostgreSQL provides the EXPLAIN command for this purpose.
Use EXPLAIN to Inspect the Execution Plan
Run the following statement on your existing PostgreSQL server:
EXPLAIN
SELECT
customer_id,
customer_name
FROM customers
WHERE customer_id = 1001;PostgreSQL returns the execution plan without executing the SELECT statement.
A simplified result might look like this:
Index Scan using customers_pkey on customers
(cost=0.29..8.30 rows=1 width=40)
Index Cond: (customer_id = 1001)This output tells us that PostgreSQL selected an index scan using the primary key index.
The cost values represent planner estimates rather than actual execution time. The rows value represents the estimated number of rows returned, and width represents the estimated average row size.
A sequential scan is not automatically a problem. If a query needs most of a table's rows, reading the table sequentially can be more efficient than accessing many individual index entries.
The important question is whether the selected plan matches the query's actual workload.
Use EXPLAIN ANALYZE for Actual Execution Details
EXPLAIN ANALYZE executes the query and adds actual execution information to the plan.
EXPLAIN (ANALYZE, BUFFERS)
SELECT
customer_id,
customer_name
FROM customers
WHERE customer_id = 1001;This provides information such as:
- Actual execution time.
- Actual number of returned rows.
- Number of rows removed by filters.
- Shared buffer hits and reads.
- Time spent in individual plan nodes.
For example, consider this simplified output:
Index Scan using customers_pkey on customers
(cost=0.29..8.30 rows=1 width=40)
(actual time=0.025..0.027 rows=1 loops=1)
Index Cond: (customer_id = 1001)
Buffers: shared hit=4
Execution Time: 0.045 msThe estimated row count is one, and the actual row count is also one. This suggests that the planner's row estimate is reasonable for this execution.
If the estimated row count is significantly different from the actual row count, the planner may be making decisions based on inaccurate assumptions.
One important consideration is that EXPLAIN ANALYZE actually executes the statement. Use it carefully for INSERT, UPDATE, DELETE, and other statements with side effects. A transaction followed by ROLLBACK can protect transactional changes in suitable cases, but it does not reverse every possible external side effect.
EXPLAIN ANALYZE also introduces measurement overhead, so its execution time should not be treated as an exact replacement for normal application latency.
Capture Important Queries From Production
Testing every SQL statement manually is not practical for a large application. Instead, identify the queries that matter most to application performance.
PostgreSQL provides the pg_stat_statements extension, which tracks planning and execution statistics for SQL statements.
Enable it through the server configuration:
shared_preload_libraries = 'pg_stat_statements'A server restart is required when adding this library to shared_preload_libraries.
Then create the extension in the database:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;You can identify frequently executed or expensive queries with a query such as:
SELECT
queryid,
calls,
total_exec_time,
mean_exec_time,
rows,
query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;This helps identify statements that consume the most total execution time.
You should also investigate queries with high average execution time, frequent calls, or significant variation between executions.
For example, a query that takes 200 milliseconds and executes 100,000 times may deserve more attention than a query that takes two seconds but runs once a day.
The pg_stat_statements extension does not provide a complete execution plan history for every query. Use it to identify important SQL statements, then capture their plans separately.
For production systems, collect representative query samples and parameter values through approved monitoring and logging practices. Avoid exposing sensitive customer information in test datasets or diagnostic logs.
Prepare a PostgreSQL 19 Test Environment
After identifying important queries, create a test environment using PostgreSQL 19.
The environment should resemble the production database as closely as possible.
A useful test environment should include:
- A representative database size.
- Similar table and index structures.
- Realistic data distribution.
- Comparable database configuration.
- Similar hardware and storage performance.
- Representative application queries and parameters.
A small development database may not reveal problems that appear only when tables contain millions of records.
For example, PostgreSQL might choose a sequential scan for a table containing a few hundred rows but use an index scan when the same table contains several million rows.
For a reliable comparison, use a restored database copy or another supported upgrade-testing approach. A major-version upgrade does not allow PostgreSQL 19 to use the same live data directory as the previous major version.
After restoring or upgrading the test database, run ANALYZE to ensure the planner has current statistics.
ANALYZE;For databases with many tables, PostgreSQL can collect statistics across the database. You can also analyze important tables individually:
ANALYZE public.customers;
ANALYZE public.orders;Do not compare plans from two environments with substantially different data distributions and assume that any difference is caused by the PostgreSQL version.
Compare Query Plans Between Versions
Now execute the same important queries against the existing PostgreSQL version and PostgreSQL 19.
Use the same SQL, equivalent parameter values, schema, indexes, and relevant configuration settings.
For example:
Join the conversation! Your thoughts help the community grow.