A PostgreSQL major version upgrade is not something that should be validated only after production has already been changed.

The application may continue to start normally while database behavior changes underneath it. Queries can choose different execution plans, extensions may behave differently, configuration defaults can change, and application code that worked against the previous PostgreSQL version may expose problems after the upgrade.

This is why a production database should be tested before the actual migration.

The goal is not simply to prove that PostgreSQL starts on the new version. The real goal is to determine whether the application, database schema, queries, extensions, jobs, connections, and operational processes continue to work correctly.

A reliable upgrade test should reproduce production conditions as closely as practical without putting the production system at risk.

Why Test Before a PostgreSQL Major Upgrade?

PostgreSQL major upgrades can introduce changes that are not visible through a simple backup and restore test.

A database may contain:

  • millions of rows
  • large indexes
  • materialized views
  • custom extensions
  • stored procedures
  • scheduled jobs
  • application-specific SQL
  • connection pooling
  • replication
  • reporting workloads
  • background workers

A development database rarely represents all of these conditions.

For example, a query may run in 20 milliseconds against a development database containing 10,000 rows.

The same query against production may involve 100 million rows and choose a very different execution plan after the upgrade.

Testing therefore needs to cover both database compatibility and application behavior.

What Should Be Tested?

A useful PostgreSQL upgrade test should cover several layers.

SQL
Production Database
        |
        +-- Schema
        +-- Data
        +-- Extensions
        +-- Queries
        +-- Indexes
        +-- Functions
        +-- Application
        +-- Background Jobs
        +-- Monitoring
        +-- Backups

Each layer can expose a different problem.

For example:

AreaWhat to Check
SchemaTables, indexes, constraints, functions
DataRow counts, important records, data types
ExtensionsVersion and compatibility
QueriesErrors and execution plans
ApplicationCRUD operations and transactions
JobsBackground processing and scheduled tasks
ConnectionsPooling and connection behavior
BackupsBackup and restore process
MonitoringMetrics, alerts, and logs
PerformanceCPU, memory, I/O, latency

Testing all of these gives a much better picture than checking only whether the database starts.

Start With a Production Inventory

Before creating the test environment, document the current production database.

Collect information such as:

SQL
SELECT version();

List databases:

SQL
SELECT datname
FROM pg_database
WHERE datistemplate = false;

List extensions:

SQL
SELECT extname, extversion
FROM pg_extension
ORDER BY extname;

List schemas:

SQL
SELECT schema_name
FROM information_schema.schemata
ORDER BY schema_name;

Also identify:

  • database size
  • largest tables
  • largest indexes
  • active connections
  • long-running queries
  • replication configuration
  • scheduled jobs
  • custom functions
  • triggers
  • foreign data wrappers
  • logical replication objects

The inventory becomes the baseline for the migration test.

Measure the Current Production Baseline

A test environment is much more useful when you know what normal production behavior looks like.

Record important metrics before the upgrade.

Examples include:

Code
Average API latency
Database CPU usage
Database memory usage
Connection count
Transaction rate
Slow query count
Read/write throughput
Replication lag
Cache hit ratio
Disk usage

For important queries, record execution plans as well.

For example:

SQL
EXPLAIN (ANALYZE, BUFFERS)
SELECT
    customer_id,
    created_at,
    total_amount
FROM orders
WHERE customer_id = 1001
ORDER BY created_at DESC
LIMIT 50;

Save the output.

After upgrading the test database, execute the same query again.

The goal is not to make every execution plan identical.

The goal is to identify meaningful changes.

Create a Realistic Test Environment

The best upgrade test uses a database that resembles production.

A practical setup is:

Code
Production PostgreSQL
        |
        | Backup / Clone
        v
Test PostgreSQL
        |
        | Upgrade
        v
Target PostgreSQL Version

The test database should contain enough real-world structure and data to expose the problems you care about.

If copying production data is restricted because of privacy or compliance requirements, create a representative dataset with the same characteristics.

For example, if production contains:

Code
200 million orders
15 million customers
3 million active subscriptions

testing against 50,000 synthetic orders will not provide enough confidence for query and index behavior.

Protect Sensitive Production Data

A production copy may contain:

  • customer information
  • email addresses
  • phone numbers
  • payment-related data
  • internal identifiers
  • access information

Do not copy sensitive production data into an environment without considering access controls and data protection requirements.

When practical, anonymize or pseudonymize sensitive fields.

For example:

Code
Production:
[email protected]

Test:
[email protected]

The structure and distribution should remain realistic enough for testing while reducing exposure.

Test the Upgrade Path

Do not assume that the final target version is the only thing worth testing.

The actual upgrade method matters.

For example, if the migration will use a dump and restore process, test that exact approach.

If the production environment will use a logical replication migration, test the replication process.

If the organization uses a supported in-place upgrade tool, validate that workflow in the test environment.

The test should answer:

Code
Can we perform the same migration process
without unexpected application or database failures?

A successful restore using one method does not automatically prove that another migration method will work.

Test Schema Compatibility

Start by validating the schema.

Compare:

  • tables
  • columns
  • data types
  • constraints
  • indexes
  • sequences
  • views
  • materialized views
  • functions
  • procedures
  • triggers
  • permissions

A useful approach is to generate schema definitions from both environments and compare them.

For example:

Bash
pg_dump --schema-only production_db > production-schema.sql

and:

Bash
pg_dump --schema-only upgraded_db > upgraded-schema.sql

Then compare the resulting files.

The exact differences depend on the upgrade method, so not every difference represents a problem.

The purpose is to identify unexpected changes.

Test PostgreSQL Extensions

Extensions deserve special attention during a major upgrade.

Check the production list:

SQL
SELECT extname, extversion
FROM pg_extension
ORDER BY extname;

Then verify that the same extensions are available and supported in the target PostgreSQL environment.

Common examples include:

Code
PostGIS
pgcrypto
uuid-ossp
pg_stat_statements
citext

The actual extension list depends on the application.

Do not assume that an extension installed in production will automatically be available in the target environment.

An application may start successfully while a feature that depends on an extension fails later.

Test Application Connections

After upgrading the test database, connect the real application to it.

This is one of the most important parts of the process.

Test:

Code
Application startup
Database connection
Authentication
Connection pooling
Transactions
Reads
Writes
Updates
Deletes
Background jobs
Reports
Scheduled tasks

For a .NET application using Npgsql, for example, the connection configuration should be tested against the upgraded database.

C#
var connectionString =
    "Host=postgres-test;Database=orders;Username=app;Password=***";

await using var connection = new NpgsqlConnection(connectionString);

await connection.OpenAsync();

await using var command =
    new NpgsqlCommand("SELECT 1", connection);

var result = await command.ExecuteScalarAsync();

A successful SELECT 1 only proves connectivity.

It does not prove application compatibility.

Real application operations must be tested.

Test Transactions

Transaction behavior should be included in the upgrade test.

For example:

C#
await using var transaction =
    await connection.BeginTransactionAsync();

try
{
    // Perform related database operations.

    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}

Test scenarios involving:

  • commit
  • rollback
  • concurrent transactions
  • deadlocks
  • transaction timeouts
  • retry behavior
  • connection failures

A database upgrade should not change application assumptions about transaction behavior without being detected during testing.

Test Your Important Queries

Do not try to test every query manually.

Instead, identify the queries that matter most to production.

Good candidates include:

  • authentication queries
  • customer lookup
  • order creation
  • payment-related queries
  • search queries
  • dashboard queries
  • reporting queries
  • batch processing
  • queue consumers
  • scheduled jobs

Record their baseline behavior.

For example:

SQL
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE customer_id = $1
ORDER BY created_at DESC
LIMIT 20;

Then compare the same query on the upgraded database.

Look for changes in:

  • execution time
  • row estimates
  • index usage
  • sequential scans
  • joins
  • sort operations
  • buffer usage
  • temporary file usage

This is especially important because a query can remain logically correct while becoming slower.

Check Execution Plan Changes

Suppose the old database uses:

Code
Index Scan

while the upgraded database chooses:

Code
Seq Scan

That is not automatically wrong.

The optimizer may have determined that the sequential scan is cheaper.

The important question is whether the decision makes sense for the actual workload.

For example:

Code
Before:
Index Scan
Execution Time: 15 ms

After:
Seq Scan
Execution Time: 2,400 ms

That difference requires investigation.

Potential causes include:

  • changed statistics
  • stale statistics
  • different cost estimates
  • changed data distribution
  • missing indexes
  • changed configuration
  • query planner changes

Do not fix a plan difference simply because it looks different. Fix it when the resulting behavior is problematic.

Refresh Statistics

After restoring or migrating a database, statistics may need attention.

Run:

SQL
ANALYZE;

For a specific table:

SQL
ANALYZE orders;

Then test important queries again.

A query planner makes decisions based partly on statistics. A test environment with incomplete or stale statistics can produce misleading results.

Test Large Tables

Small databases hide performance problems.

Identify your largest tables:

SQL
SELECT
    schemaname,
    relname,
    pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 20;

Pay particular attention to:

  • heavily queried tables
  • large indexes
  • partitioned tables
  • frequently updated tables
  • tables used in reporting
  • tables involved in joins

If production performance depends on table size, the upgrade test should reflect that size.

Test Indexes

Verify that important indexes exist after the migration.

You can inspect indexes using:

SQL
SELECT
    schemaname,
    tablename,
    indexname,
    indexdef
FROM pg_indexes
WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
ORDER BY schemaname, tablename, indexname;

Then compare important indexes between the production baseline and upgraded environment.

Do not assume that an index definition alone proves performance.

Run the important queries and inspect their execution plans.

Test Stored Functions and Procedures

Applications sometimes depend heavily on database-side logic.

Test:

  • functions
  • procedures
  • triggers
  • generated columns
  • views
  • materialized views

For example:

SQL
SELECT *
FROM calculate_customer_balance(1001);

If a function is part of a critical transaction, include that transaction in integration testing.

Database-side code can fail independently of application code.

Test Background Jobs

A web application may work perfectly while background processing is broken.

Test:

Code
Queue consumers
Scheduled jobs
Data synchronization
Email processing
Report generation
Cleanup jobs
ETL processes
Notification workers

For example, if a background worker executes:

SQL
SELECT id
FROM jobs
WHERE status = 'pending'
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 10;

verify that the complete worker workflow still behaves correctly.

Do not test only the SQL statement. Test the application behavior around it.

Test Connection Pooling

Connection behavior can change under load.

If the application uses a connection pool, test:

  • normal connection count
  • connection reuse
  • maximum pool size
  • connection timeout
  • command timeout
  • connection failures
  • application restarts
  • database restarts

A simple application test that opens one connection does not represent production traffic.

Run realistic concurrent requests against the upgraded database.

Perform Load Testing

Performance testing becomes much more useful when it resembles actual production traffic.

For example:

Code
100 requests/sec
70% reads
20% updates
10% inserts

The exact numbers should come from production metrics.

Measure:

Code
API latency
Database latency
CPU
Memory
I/O
Connection count
Transactions/sec
Error rate
Lock waits

Compare the old and upgraded environments.

The goal is to identify regressions before production traffic finds them.

Test Failure Scenarios

A migration test should include failure behavior.

For example:

  • database connection is interrupted
  • transaction fails
  • query times out
  • connection pool is exhausted
  • replication falls behind
  • application restarts
  • database restarts
  • background job fails

Check whether the application:

  • retries safely
  • avoids duplicate writes
  • reports useful errors
  • recovers connections
  • preserves transaction integrity

An upgrade is not only about successful requests.

Failure behavior matters just as much.

Test Backups and Restore

Before approving the migration, verify that the backup and restore process works with the target version.

A backup is useful only if it can actually be restored.

Test:

Code
Backup
   |
   v
Restore
   |
   v
Start PostgreSQL
   |
   v
Run validation queries
   |
   v
Start application
   |
   v
Run smoke tests

Validate important objects and data after restoration.

Check:

  • table counts
  • row counts
  • indexes
  • extensions
  • permissions
  • application connectivity

Validate Data After the Upgrade

Data correctness should be tested explicitly.

Do not rely only on the application.

Useful checks include:

SQL
SELECT COUNT(*) FROM customers;
SELECT COUNT(*) FROM orders;
SELECT COUNT(*) FROM payments;

For important numeric data:

SQL
SELECT
    COUNT(*) AS order_count,
    SUM(total_amount) AS total_amount
FROM orders;

For important date ranges:

SQL
SELECT
    MIN(created_at),
    MAX(created_at)
FROM orders;

Compare these results against the production baseline.

For very large databases, use representative validation rather than attempting to manually inspect every row.

Test Replication

If production uses replication, include it in the upgrade testing.

Test:

  • replica startup
  • replication connection
  • replication lag
  • failover
  • read-only behavior
  • monitoring
  • recovery

If the migration strategy involves replication-based cutover, this becomes even more important.

The test should reproduce the actual topology as closely as practical.

Test Monitoring and Alerts

Database migration can expose gaps in monitoring.

Verify that existing monitoring still detects:

  • high CPU
  • high connection usage
  • slow queries
  • replication lag
  • disk growth
  • failed connections
  • lock contention
  • backup failures

Do not wait until production to discover that a database metric disappeared after the upgrade.

Run a Production-Like Smoke Test

Before the migration is approved, run a repeatable smoke test.

For example:

Code
1. Application starts
2. Login succeeds
3. Customer can be loaded
4. New order can be created
5. Order can be updated
6. Payment record can be read
7. Background job processes successfully
8. Report loads
9. Important queries remain within target latency
10. No unexpected database errors appear

This gives the team a simple acceptance test for the upgraded environment.

Common Mistakes

MistakeWhy It Causes ProblemsBetter Approach
Testing only PostgreSQL startupDoes not prove application compatibilityTest real application operations
Using a tiny databaseHides query and index problemsUse production-like data volume
Ignoring extensionsFeatures may fail after migrationInventory and test every extension
Comparing only row countsData can be structurally correct but functionally wrongTest application behavior
Skipping execution plansPerformance regressions may go unnoticedCompare important queries
Testing only happy pathsRecovery problems remain hiddenTest failures and retries
Ignoring background jobsNon-web workloads may breakInclude workers and scheduled tasks
Forgetting backupsRecovery may fail when neededPerform a restore test
Assuming every plan change is badPlanner behavior can legitimately changeCompare actual performance
Testing a different migration methodProduction may fail despite successful testingTest the real upgrade procedure

Build an Upgrade Readiness Report

After testing, document the results.

A simple report can contain:

AreaResultNotes
SchemaPassedNo unexpected differences
ExtensionsPassedRequired extensions available
Data validationPassedKey counts match
API testsPassedNo application errors
Query performancePassedNo significant regressions
Background jobsPassedJobs processed correctly
ReplicationPassedWithin expected lag
Backup restorePassedRecovery tested
MonitoringPassedAlerts operational
Load testingReviewOne query needs tuning

This makes the migration decision measurable.

When the Test Finds a Problem

Do not immediately cancel the upgrade.

Classify the problem first.

SQL
Problem
   |
   +-- Compatibility issue
   +-- Performance issue
   +-- Configuration issue
   +-- Extension issue
   +-- Application issue
   +-- Migration process issue

Then determine whether the problem can be fixed before production.

For example:

Code
Query became slower
        |
        v
Compare execution plans
        |
        v
Check statistics
        |
        v
Check index
        |
        v
Retest

A failed upgrade test is useful because it identifies the problem while there is still time to fix it.

Advantages of Testing Before Migration

AdvantageDescription
Lower production riskProblems are found before cutover
Better performance confidenceImportant queries can be compared
Safer rollback planningMigration steps are tested beforehand
Better application confidenceReal application operations are validated
Extension compatibilityUnsupported or problematic extensions are identified
Operational readinessBackups, monitoring, and recovery are tested
Faster migrationKnown problems can be resolved before the maintenance window

Disadvantages and Trade-Offs

Testing a production database upgrade requires effort.

ChallengeImpact
Large test databasesRequire storage and infrastructure
Data anonymizationAdds preparation work
Load testingRequires additional tooling
Environment duplicationCan increase infrastructure cost
Test maintenanceProduction changes may require refreshing the test environment
Long-running testsLarge databases can take significant time to validate

These costs are generally much smaller than discovering an upgrade problem after production traffic has already moved to the new database.

PostgreSQL Upgrade Readiness Checklist

Before upgrading the production database, verify:

  • Production database version is documented.
  • Target PostgreSQL version is defined.
  • Upgrade method has been tested.
  • Database size is documented.
  • Important tables and indexes are identified.
  • Extensions are inventoried.
  • Schema has been compared.
  • Production-like data is available for testing.
  • Sensitive test data is protected.
  • Important queries have baseline execution plans.
  • Query performance has been compared.
  • Application integration tests pass.
  • Transactions have been tested.
  • Background jobs have been tested.
  • Connection pooling has been tested.
  • Load testing has been completed.
  • Failure scenarios have been tested.
  • Replication has been tested where applicable.
  • Backup and restore have been validated.
  • Monitoring and alerts have been checked.
  • Production smoke tests are documented.
  • Rollback or recovery procedures are understood.
  • Known issues are documented and accepted.

Final Thoughts

A PostgreSQL major version upgrade should be treated as an application and infrastructure change, not just a database maintenance task.

The safest approach is to create a production-like test environment, use the same upgrade method planned for production, validate the schema and extensions, compare important query plans, run realistic application workloads, test background processing, verify backups, and check recovery behavior.

The most valuable result of this testing is not a simple "upgrade succeeded" message.

It is knowing what will change, which parts of the system are affected, and what needs to be fixed before production is touched.

A successful database upgrade is not just a PostgreSQL server running on the new version. It is the application continuing to behave correctly after the database underneath it has changed.