Sub topic 9
After the upgrade: statistics, extensions and cleanup
This chapter assumes you have completed the earlier steps. The new cluster was initialized, pg_upgrade --check passed, and the real upgrade (pg_upgrade without --check) finished without errors. You should be comfortable with psql, pg_ctl and the idea of an extension. The commands use the same placeholder paths as the rest of the tutorial (/opt/pg17, /data/pg17).
A successful pg_upgrade run means the data was moved. It does not mean the new cluster is ready for production traffic. Three things are still missing: planner statistics, updated extension objects, and a tidy-up of the old cluster. Do them in that order.
What pg_upgrade leaves undone
pg_upgrade moves the schema and the data files. It does not carry over everything that makes a cluster work well day to day.
| Item | State after upgrade | What you do |
|---|---|---|
| Table and index data | Present | Verify with checks |
| Planner statistics (`pg_statistic`) | Missing when upgrading from PostgreSQL 17 or earlier; copied in 18 and later | Rebuild with `vacuumdb` |
| Extended statistics (`CREATE STATISTICS`) | Definitions kept, data missing | Rebuild with `vacuumdb` |
| Extension objects | Still at the old extension version | `ALTER EXTENSION ... UPDATE` |
| Cumulative statistics (`pg_stat_*` views) | Reset | Expect empty counters |
| `postgresql.conf`, `pg_hba.conf` | Not copied | Reconcile by hand |
| Old cluster | Still on disk | Remove after the rollback window |
The sequence of this chapter looks like this:
Starting the new cluster and rebuilding statistics
Planner statistics are the numbers the query planner uses to estimate how many rows a filter will return. They come from ANALYZE. If they are missing, the planner falls back on default guesses, and queries that ran in milliseconds can turn into sequential scans or bad join orders. Before PostgreSQL 18, pg_upgrade did not copy them, so every table starts with no statistics.
Start the new cluster and rebuild statistics in one step:
/opt/pg17/bin/pg_ctl -D /data/pg17 -l /data/pg17/server.log start
/opt/pg17/bin/vacuumdb --all --analyze-in-stages--analyze-in-stages runs ANALYZE over every database three times, with a growing level of detail:
- The first pass uses
default_statistics_target = 1. It is very fast and gives the planner only coarse numbers, but those are far better than none. - The second pass uses a target of 10.
- The final pass uses your configured
default_statistics_target, which gives the normal full-quality statistics.
The benefit is that queries become usable after the first pass, not after the whole analysis finishes. On a database with thousands of large tables, the full pass can take a long time.
Two practical notes:
vacuumdbruns as a client, so it needs a working connection. If you changedpg_hba.confto lock out applications during the upgrade, use a superuser connection from the local machine.- You can speed it up with
--jobs=N, which analyzes several tables in parallel. Each job opens its own connection, so checkmax_connectionsfirst.
/opt/pg17/bin/vacuumdb --all --analyze-in-stages --jobs=4Statistics are preserved in newer releases
PostgreSQL 18 changed this behavior: pg_upgrade can carry over the main planner statistics when upgrading to version 18 or later. Extended statistics are still not transferred. For that case vacuumdb gained --missing-stats-only, which analyzes only the tables or columns that still lack statistics. Check the release notes of the target version to see which situation you are in. If you are unsure, running --analyze-in-stages is always safe, only slower.
Checking for tables without statistics
You can see which tables still have no statistics. Run this in each database as a superuser, because pg_statistic is restricted:
SELECT c.oid::regclass AS table_name
FROM pg_class AS c
JOIN pg_namespace AS n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'm')
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND NOT EXISTS (SELECT 1 FROM pg_statistic AS s WHERE s.starelid = c.oid)
ORDER BY 1;Empty tables also show up here, because ANALYZE stores nothing for them. Tables with rows that appear in this list after vacuumdb finished deserve a closer look.
Updating extensions
An extension has two versions that matter. The first is the version of its shared library (the compiled .so file), which comes from the package you installed for the new PostgreSQL version. The second is the version of its SQL objects (functions, types, operators) recorded in the database. pg_upgrade copies the SQL objects as they were, so they stay at the old extension version, while the new binaries contain newer code. Often the old objects still work, but new features and bug fixes only appear after an update.
List the extensions that are behind. Run this in every database, since extensions are installed per database:
SELECT name, installed_version, default_version
FROM pg_available_extensions
WHERE installed_version IS NOT NULL
AND installed_version <> default_version
ORDER BY name;Each row is an extension that can be updated. Update one with:
ALTER EXTENSION pg_stat_statements UPDATE;Without a target version, UPDATE moves to the default_version shown above. Some extensions need extra care:
pg_upgradecan write a file namedupdate_extensions.sqlin the directory where you ran it. It contains anALTER EXTENSION ... UPDATEfor each extension that needs it, and you run it withpsql -f update_extensions.sql(the script connects to each database itself). Whether the file appears depends on the version, so check the end of thepg_upgradeoutput.- PostGIS and similar extensions that depend on other libraries have their own upgrade notes. Read them before running
ALTER EXTENSION, because some require updating a dependency first, or running a function after the update. - Extensions that were not installed for the new version would have blocked the upgrade earlier, since
pg_upgrade --checkverifies that the libraries load.
Reconcile configuration and smoke test
Configuration files are not carried over. The new data directory has the defaults written by initdb. Compare them with the old files and port the settings you still want:
diff /data/pg16/postgresql.conf /data/pg17/postgresql.conf
diff /data/pg16/pg_hba.conf /data/pg17/pg_hba.confExpect noise. Some parameters were renamed or removed between versions, and defaults change. Do not copy the old file over the new one. Edit the new file, and look at each changed setting against the release notes. After changes, reload with pg_ctl reload or restart if a setting requires it (the server log tells you).
Then check the basics before sending production traffic:
- Compare row counts or checksums for a handful of important tables against the old cluster. The old cluster can be read from a backup if you used link mode (see below).
- Run the application's own test suite, or at least its critical queries, and compare plans for the slowest ones with
EXPLAIN. - Confirm that sequences return sensible values.
pg_upgradepreserves them, sonextvalshould continue where it stopped. - Check that autovacuum is running:
SHOW autovacuum;and look for worker processes inpg_stat_activity. - Re-enable anything you turned off for the upgrade: scheduled jobs, monitoring alerts, connection poolers, and
pg_hba.confrules.
Take a new backup
After the upgrade, existing backups and WAL archives belong to the old cluster. A base backup from PostgreSQL 16 cannot be restored into a version 17 server, and old WAL files cannot be replayed onto the new cluster. Until you take a new base backup of the upgraded cluster, you have no backup for it. Start one as soon as the smoke tests pass, and point your archive settings to a fresh location if your tooling requires it.
Cleaning up the old cluster
Wait until you are sure you will not roll back. A sensible rule is to keep the old cluster until the new one has run through a full business cycle, such as a month-end close, and a fresh backup has been tested by restoring it.
When pg_upgrade finishes, it writes a script named delete_old_cluster.sh into the current directory. For a cluster with tablespaces, the script removes the old data directory and the old version's subdirectories in each tablespace. Read it before you run it:
cat delete_old_cluster.sh
sh delete_old_cluster.shIf you did not use a script, remove the old data directory yourself. In link mode this is safe for the new cluster: files in the old directory that are hard links lose one name, and the new cluster keeps its own. Then finish the job:
- Uninstall the old version's packages, or at least stop and disable its service unit, so a reboot does not try to start it.
- Remove
update_extensions.sql,delete_old_cluster.shand thepg_upgrade_output.ddirectory once you no longer need the logs. On success, newer versions delete the log directory automatically unless you passed--retain. After a failure, the logs remain and are the first thing to read. - Update the service name, the
PATH, environment files, backup jobs and monitoring to the new version and port.
Common mistakes after the upgrade
- Opening the application to users before the first analysis pass finishes. Queries run with default estimates and can be very slow.
- Forgetting that statistics are per database.
vacuumdb --allcovers every database, while a plainANALYZEinpsqlcovers only the current one. - Running
ALTER EXTENSION ... UPDATEin one database and assuming it applies to all. - Deleting the old cluster the same day, then discovering a problem that needs the old data.
- Leaving old backups as the only backups. They cannot restore the new version.
Exercise
After a pg_upgrade from PostgreSQL 16 to 17, users report that a report query which took 200 ms before now takes 40 seconds, although the data is identical. What is the most likely cause, and what command do you run to fix it for all databases?
Show answer
Version 17 did not receive the planner statistics from version 16, so the planner is guessing row counts and picks a bad plan. Run vacuumdb --all --analyze-in-stages (optionally with --jobs=N). The first pass gives rough statistics quickly, and later passes refine them.
Exercise
You run SELECT name, installed_version, default_version FROM pg_available_extensions WHERE installed_version IS NOT NULL AND installed_version <> default_version; in the database postgres and get no rows. Does that mean no extensions anywhere need updating?
Show answer
No. Extensions are installed per database, so the query shows only extensions in the database you are connected to. Run it in every database, or use the update_extensions.sql script if pg_upgrade produced one. Update each outdated extension with ALTER EXTENSION name UPDATE;, not by dropping it.
Exercise
You upgraded with --link and started the new cluster. Two days later you want to go back to the old version. Why is simply starting the old cluster not an option, and what do you restore from?
Show answer
The new cluster has been writing to the same data files through hard links, so the old cluster's files are no longer consistent with its own state, and starting it could corrupt data. pg_upgrade also renames the old pg_control file to block the start. You must restore from a backup taken before the upgrade, which loses any changes made since, or use a copy-mode upgrade next time if a quick rollback matters more than speed.