PG_UPGRADE(1)
PG_UPGRADE(1) π
PostgreSQL 18.6 Documentation β yeah bestie, we're reading the actual docs, and honestly? iconic of you.
β¨ NAME β¨
pg_upgrade β upgrade a PostgreSQL server instance. That's it, that's the whole job, and she does it beautifully. π
πΈ SYNOPSIS πΈ
pg_upgrade -b oldbindir [-B newbindir] -d oldconfigdir -D newconfigdir
[option...]
π¦ DESCRIPTION π¦
Okay so. pg_upgrade (fun fact: she used to be called pg_migrator, glow-up era π
) lets you take data stored in PostgreSQL data files and bump it up to a later PostgreSQL major version β WITHOUT the whole dump/restore saga that major version upgrades usually demand. Like, going from 12.14 to 13.10, or from 14.9 to 15.5. β¨
But listen β you do not need this for minor version upgrades. Like from 12.7 to 12.8, or 14.1 to 14.5. Those are chill, don't bother her. π
Here's the tea: major PostgreSQL releases regularly add new features, and those features often change the layout of the system tables. But the internal data storage format? Rarely changes. pg_upgrade literally uses this fact to do rapid upgrades by creating new system tables and justβ¦ reusing the old user data files. No cap, that's the whole trick. π
β οΈ But hypothetically, if a future major release ever changed the data storage format in a way that made the old data format unreadable, pg_upgrade would not be usable for those upgrades. (The community will attempt to avoid such situations. They're looking out for us fr fr. π«Ά)
pg_upgrade does her best to make sure the old and new clusters are binary-compatible β like, checking for compatible compile-time settings, including 32/64-bit binaries. And it's important that any external modules are also binary compatible, though this cannot be checked by pg_upgrade. π (she can't see everything, bestie!)
pg_upgrade supports upgrades from 9.2.X and later to the current major release of PostgreSQL, including snapshot and beta releases. π
Warning Upgrading a cluster causes the destination to execute arbitrary code of the source superusers' choice. Ensure that the source superusers are trusted before upgrading. π Like, actually trusted. This is not a vibe check you skip.
π OPTIONS π
pg_upgrade accepts the following command-line arguments:
-bbindir,--old-bindir=bindir β the old PostgreSQL executable directory; environment variablePGBINOLD. π§-Bbindir,--new-bindir=bindir β the new PostgreSQL executable directory; default is the directory wherepg_upgraderesides; environment variablePGBINNEW.-c,--checkβ check clusters only, don't change any data. A little peek, no touching. π-dconfigdir,--old-datadir=configdir β the old database cluster configuration directory; environment variablePGDATAOLD.-Dconfigdir,--new-datadir=configdir β the new database cluster configuration directory; environment variablePGDATANEW.-jnjobs,--jobs=njobs β number of simultaneous connections and processes/threads to use. More jobs = more chaos = usually faster. π₯-k,--linkβ use hard links instead of copying files to the new cluster.-N,--no-syncβ By default,pg_upgradewill wait for all files of the upgraded cluster to be written safely to disk. This option causespg_upgradeto return without waiting, which is faster, but means that a subsequent operating system crash can leave the data directory corrupt. Generally, this option is useful for testing but should not be used on a production installation. π-ooptions,--old-optionsoptions β options to be passed directly to the oldpostgrescommand; multiple option invocations are appended.-Ooptions,--new-optionsoptions β options to be passed directly to the newpostgrescommand; multiple option invocations are appended.-pport,--old-port=port β the old cluster port number; environment variablePGPORTOLD.-Pport,--new-port=port β the new cluster port number; environment variablePGPORTNEW.-r,--retainβ retain SQL and log files even after successful completion. Keeping the receipts, love that for her. π§Ύ-sdir,--socketdir=dir β directory to use for postmaster sockets during upgrade; default is current working directory; environment variablePGSOCKETDIR.-Uusername,--username=username β cluster's install user name; environment variablePGUSER.-v,--verboseβ enable verbose internal logging. She will tell you EVERYTHING. π£οΈ-V,--versionβ display version information, then exit.--cloneβ Use efficient file cloning (also known as "reflinks" on some systems) instead of copying files to the new cluster. This can result in near-instantaneous copying of the data files, giving the speed advantages of-k/--linkwhile leaving the old cluster untouched. β¨
File cloning is only supported on some operating systems and file systems. If it is selected but not supported, the pg_upgrade run will error. At present, it is supported on Linux (kernel 4.5 or later) with Btrfs and XFS (on file systems created with reflink support), and on macOS with APFS.
--copyβ Copy files to the new cluster. This is the default. (See also--link,--clone,--copy-file-range, and--swap.)--copy-file-rangeβ Use thecopy_file_rangesystem call for efficient copying. On some file systems this gives results similar to--clone, sharing physical disk blocks, while on others it may still copy blocks, but do so via an optimized path. At present, it is supported on Linux and FreeBSD. π§--no-statisticsβ Do not restore statistics from the old cluster into the new cluster.--set-char-signedness=option β Manually set the default char signedness of new clusters. Possible values aresignedandunsigned.
In the C language, the default signedness of the char type (when not explicitly specified) varies across platforms. For example, char defaults to signed char on x86 CPUs but to unsigned char on ARM CPUs.
Starting from PostgreSQL 18, database clusters maintain their own default char signedness setting, which can be used to ensure consistent behavior across platforms with different default char signedness. By default, pg_upgrade preserves the char signedness setting when upgrading from an existing cluster. However, when upgrading from PostgreSQL 17 or earlier, pg_upgrade adopts the char signedness of the platform on which it was built.
This option allows you to explicitly set the default char signedness for the new cluster, overriding any inherited values. There are two specific scenarios where this option is relevant:
- If you are planning to migrate to a different platform after the upgrade, you should not use this option. The default behavior is right in this case. Instead, perform the upgrade on the original platform without this flag, and then migrate the cluster afterward. This is the recommended and safest approach. π«Ά
- If you have already migrated the cluster to a platform with different char signedness (for example, from an x86-based system to an ARM-based system), you should use this option to specify the signedness matching the original platform's default char signedness. Additionally, it's essential not to modify any data files between migrating data files and running
pg_upgrade.pg_upgradeshould be the first operation that starts the cluster on the new platform. β
--swapβ Move the data directories from the old cluster to the new cluster. Then, replace the catalog files with those generated for the new cluster. This mode can outperform--link,--clone,--copy, and--copy-file-range, especially on clusters with many relations.
However, this mode creates many garbage files in the old cluster, which can prolong the file synchronization step if --sync-method=syncfs is used. Therefore, it is recommended to use --sync-method=fsync with --swap. ποΈ
Additionally, once the file transfer step begins, the old cluster will be destructively modified and therefore will no longer be safe to start. See Step 17 for details. π
--sync-method=method β When set tofsync, which is the default,pg_upgradewill recursively open and synchronize all files in the upgraded cluster's data directory. The search for files will follow symbolic links for the WAL directory and each configured tablespace.
On Linux, syncfs may be used instead to ask the operating system to synchronize the whole file systems that contain the upgraded cluster's data directory, its WAL files, and each tablespace. See recovery_init_sync_method for information about the caveats to be aware of when using syncfs.
This option has no effect when --no-sync is used.
-?,--helpβ show help, then exit.
π USAGE π
These are the steps to perform an upgrade with pg_upgrade:
Note The steps to upgrade logical replication clusters are not covered here; refer to Section 29.13 for details. (Different lore, different page. π)
- Optionally move the old cluster: If you are using a version-specific installation directory, e.g.,
/opt/PostgreSQL/18, you do not need to move the old cluster. The graphical installers all use version-specific installation directories.
If your installation directory is not version-specific, e.g., /usr/local/pgsql, it is necessary to move the current PostgreSQL install directory so it does not interfere with the new PostgreSQL installation. Once the current PostgreSQL server is shut down, it is safe to rename the PostgreSQL installation directory; assuming the old directory is /usr/local/pgsql, you can do:
mv /usr/local/pgsql /usr/local/pgsql.old
to rename the directory.
- For source installs, build the new version: Build the new PostgreSQL source with
configureflags that are compatible with the old cluster.pg_upgradewill checkpg_controldatato make sure all settings are compatible before starting the upgrade. π - Install the new PostgreSQL binaries: Install the new server's binaries and support files.
pg_upgradeis included in a default installation.
For source installs, if you wish to install the new server in a custom location, use the prefix variable:
make prefix=/usr/local/pgsql.new install
- Initialize the new PostgreSQL cluster: Initialize the new cluster using
initdb. Again, use compatibleinitdbflags that match the old cluster. Many prebuilt installers do this step automatically. There is no need to start the new cluster. π±
- Install extension shared object files π β so many extensions and custom modules (whether they come from contrib or from somewhere else entirely) rely on shared object files, a.k.a. DLLs, like
pgcrypto.so. If your old cluster was using them, you need the shared object files that match the new server binary installed in the new cluster too β usually that's just an operating-system-commands situation, nbd. π«Ά
Do NOT load the schema definitions, likeCREATE EXTENSION pgcrypto, bestie. They will get duplicated from the old cluster and that's not the vibe. π If extension updates are available,pg_upgradewill tell you and make a script you can run later to update them. β¨
- Copy custom full-text search files π¦ β grab any custom full text search files (dictionary, synonym, thesaurus, stop words) from the old cluster and copy them over to the new one.
- Adjust authentication π β
pg_upgradeconnects to the old and new servers several times, so you might wanna set authentication topeerinpg_hba.conf, or use a~/.pgpassfile (see Section 32.16). - Stop both servers π β make sure both database servers are stopped. On Unix, like:
pg_ctl -D /opt/PostgreSQL/12 stop
pg_ctl -D /opt/PostgreSQL/18 stop
or on Windows, using the proper service names:
NET STOP postgresql-12
NET STOP postgresql-18
Streaming replication and log-shipping standby servers must be running during this shutdown so they receive all the changes. π
- Prepare for standby server upgrades π§ β if you're upgrading standby servers using the methods in section Step 11, verify that the old standby servers are caught up by running
pg_controldataagainst the old primary and standby clusters. Verify that the βLatest checkpoint locationβ values match in all clusters. Also, make surewal_levelis not set tominimalin thepostgresql.conffile on the new primary cluster. β - Run pg_upgrade π₯ β always run the
pg_upgradebinary of the new server, never the old one.pg_upgraderequires the specification of the old and new cluster's data and executable (bin) directories. You can also specify user and port values, and whether you want the data files linked, cloned, or swapped instead of the default copy behavior.
If you use link mode, the upgrade will be much faster (no file copying) and use less disk space β but you will not be able to access your old cluster once you start the new cluster after the upgrade. Link mode also requires that the old and new cluster data directories be in the same file system. (Tablespaces and pg_wal can be on different file systems.) Clone mode provides the same speed and disk space advantages but does not cause the old cluster to be unusable once the new cluster is started. Clone mode also requires that the old and new data directories be in the same file system. This mode is only available on certain operating systems and file systems. Swap mode may be the fastest if there are many relations, but you will not be able to access your old cluster once the file transfer step begins. Swap mode also requires that the old and new cluster data directories be in the same file system.
Setting --jobs to 2 or higher allows pg_upgrade to process multiple databases and tablespaces in parallel. A good starting point is the number of CPU cores on the machine. This option can substantially reduce the upgrade time for multi-database and multi-tablespace servers. π
For Windows users, you must be logged into an administrative account, and then run pg_upgrade with quoted directories, e.g.:
pg_upgrade.exe
--old-datadir "C:/Program Files/PostgreSQL/12/data"
--new-datadir "C:/Program Files/PostgreSQL/18/data"
--old-bindir "C:/Program Files/PostgreSQL/12/bin"
--new-bindir "C:/Program Files/PostgreSQL/18/bin"
Once started, pg_upgrade will verify the two clusters are compatible and then do the upgrade. You can use pg_upgrade --check to perform only the checks, even if the old server is still running. pg_upgrade --check will also outline any manual adjustments you will need to make after the upgrade. If you are going to be using link, clone, copy-file-range, or swap mode, you should use the option --link, --clone, --copy-file-range, or --swap with --check to enable mode-specific checks. pg_upgrade requires write permission in the current directory. π
Obviously, no one should be accessing the clusters during the upgrade. pg_upgrade defaults to running servers on port 50432 to avoid unintended client connections. You can use the same port number for both clusters when doing an upgrade because the old and new clusters will not be running at the same time. However, when checking an old running server, the old and new port numbers must be different.
If an error occurs while restoring the database schema, pg_upgrade will exit and you will have to revert to the old cluster as outlined in Step 17 below. To try pg_upgrade again, you will need to modify the old cluster so the pg_upgrade schema restore succeeds. If the problem is a contrib module, you might need to uninstall the contrib module from the old cluster and install it in the new cluster after the upgrade, assuming the module is not being used to store user data. π
- Upgrade streaming replication and log-shipping standby servers π β if you used link mode and have Streaming Replication (see Section 26.2.5) or Log-Shipping (see Section 26.2) standby servers, you can follow these steps to quickly upgrade them. You will not be running
pg_upgradeon the standby servers, but ratherrsyncon the primary. Do not start any servers yet.
If you did not use link mode, do not have or do not want to use rsync, or want an easier solution, skip the instructions in this section and simply recreate the standby servers once pg_upgrade completes and the new primary is running.
- Install the new PostgreSQL binaries on standby servers β make sure the new binaries and support files are installed on all standby servers.
- Make sure the new standby data directories do not exist β make sure the new standby data directories do not exist or are empty. If
initdbwas run, delete the standby servers' new data directories. - Install extension shared object files β install the same extension shared object files on the new standbys that you installed in the new primary cluster.
- Stop standby servers β if the standby servers are still running, stop them now using the above instructions.
- Save configuration files β save any configuration files from the old standbys' configuration directories you need to keep, e.g.,
postgresql.conf(and any files included by it),postgresql.auto.conf,pg_hba.conf, because these will be overwritten or removed in the next step. π«Ά - Run rsync β when using link mode, standby servers can be quickly upgraded using
rsync. To accomplish this, from a directory on the primary server that is above the old and new database cluster directories, run this on the primary for each standby server:
rsync --archive --delete --hard-links --size-only --no-inc-recursive old_cluster new_cluster remote_dir
where old_cluster and new_cluster are relative to the current directory on the primary, and remote_dir is above the old and new cluster directories on the standby. The directory structure under the specified directories on the primary and standbys must match. Consult the rsync manual page for details on specifying the remote directory, e.g.,
rsync --archive --delete --hard-links --size-only --no-inc-recursive /opt/PostgreSQL/12 \
/opt/PostgreSQL/18 standby.example.com:/opt/PostgreSQL
You can verify what the command will do using rsync's --dry-run option. While rsync must be run on the primary for at least one standby, it is possible to run rsync on an upgraded standby to upgrade other standbys, as long as the upgraded standby has not been started.
What this does is to record the links created by pg_upgrade's link mode that connect files in the old and new clusters on the primary server. It then finds matching files in the standby's old cluster and creates links for them in the standby's new cluster. Files that were not linked on the primary are copied from the primary to the standby. (They are usually small.) This provides rapid standby upgrades. Unfortunately, rsync needlessly copies files associated with temporary and unlogged tables because these files don't normally exist on standby servers. π
If you have tablespaces, you will need to run a similar rsync command for each tablespace directory, e.g.:
rsync --archive --delete --hard-links --size-only --no-inc-recursive /vol1/pg_tblsp/PG_12_201909212 \
/vol1/pg_tblsp/PG_18_202307071 standby.example.com:/vol1/pg_tblsp
If you have relocated pg_wal outside the data directories, rsync must be run on those directories too.
- Configure streaming replication and log-shipping standby servers β configure the servers for log shipping. (You do not need to run
pg_backup_start()andpg_backup_stop()or take a file system backup as the standbys are still synchronized with the primary.) If the old primary is prior to version 17.0, then no slots on the primary are copied to the new standby, so all the slots on the old standby must be recreated manually. If the old primary is version 17.0 or later, then only logical slots on the primary are copied to the new standby, but other slots on the old standby are not copied, so must be recreated manually.
- Restore pg_hba.conf π β if you modified
pg_hba.conf, restore its original settings. It might also be necessary to adjust other configuration files in the new cluster to match the old cluster, e.g.,postgresql.conf(and any files included by it),postgresql.auto.conf. - Start the new server π β the new server can now be safely started, and then any
rsync'ed standby servers.
- Post-upgrade processing π
β if literally any post-upgrade processing is needed,
pg_upgradewill throw warnings at you as it finishes up. It also generates script files that you, the administrator, have to run yourself. Those script files connect to each database that needs the post-upgrade work done. Every script gets run like this:
psql --username=postgres --file=script.sql postgres
You can run the scripts in any order, and once you've run them you can just delete them. ποΈ
β οΈ Caution β bestie, generally it is unsafe to access tables that are referenced in rebuild scripts until those rebuild scripts have run all the way to completion. Doing that could give you incorrect results or poor performance. Tables that are not referenced in rebuild scripts? Those you can access immediately. no cap.
- Statistics π β unless you passed the
--no-statisticsoption,pg_upgradewill transfer most optimizer statistics from the old cluster to the new cluster. Notice how I said most: it does not transfer all statistics β like the ones you created explicitly withCREATE STATISTICS(CREATE_STATISTICS(7)), custom statistics added by an extension, or statistics collected by the cumulative statistics system.
And because not all the statistics get transferred by pg_upgrade, you'll be told to run commands to regenerate that info at the end of the upgrade. You might also need to set connection parameters so they match your new cluster. β¨
First up: use vacuumdb --all --analyze-in-stages --missing-stats-only to quickly generate minimal optimizer statistics for relations that don't have any. Then use vacuumdb --all --analyze-only to make sure all relations have updated cumulative statistics for triggering vacuum and analyze. For both commands, using --jobs can speed things up. πβοΈ And if vacuum_cost_delay is set to a non-zero value, you can override that to speed up statistics generation using PGOPTIONS, like:
PGOPTIONS='-c vacuum_cost_delay=0' vacuumdb ....
- Delete old cluster π§Ή β once you're satisfied with the upgrade, you can delete the old cluster's data directories by running the script that was mentioned when
pg_upgradecompleted. (Heads up: automatic deletion is not possible if you have user-defined tablespaces inside the old data directory.) You can also delete the old installation directories, likebinandshare. - Reverting to old cluster β©οΈ β if, after running
pg_upgrade, you wish to revert to the old cluster, there are several options:- If the
--checkoption was used, the old cluster was unmodified; it can be restarted. - If neither
--linknor--swapwas used, the old cluster was unmodified; it can be restarted. - If the
--linkoption was used, the data files might be shared between the old and new cluster:- If
pg_upgradeaborted before linking started, the old cluster was unmodified; it can be restarted. - If you did not start the new cluster, the old cluster was unmodified except that, when linking started, a
.oldsuffix was appended to$PGDATA/global/pg_control. To reuse the old cluster, remove the.oldsuffix from$PGDATA/global/pg_control; you can then restart the old cluster. - If you did start the new cluster, it has written to shared files and it is unsafe to use the old cluster. The old cluster will need to be restored from backup in this case. π
- If
- If the
--swapoption was used, the old cluster might be destructively modified:- If
pg_upgradeaborts before reporting that the old cluster is no longer safe to start, the old cluster was unmodified; it can be restarted. - If
pg_upgradehas reported that the old cluster is no longer safe to start, the old cluster was destructively modified. The old cluster will need to be restored from backup in this case.
- If
- If the
πΈ ENVIRONMENT πΈ
Some environment variables can be used to provide defaults for command-line options:
PGBINOLDβ the old PostgreSQL executable directory; that's option-b/--old-bindir.PGBINNEWβ the new PostgreSQL executable directory; that's option-B/--new-bindir.PGDATAOLDβ the old database cluster configuration directory; that's option-d/--old-datadir.PGDATANEWβ the new database cluster configuration directory; that's option-D/--new-datadir.PGPORTOLDβ the old cluster port number; that's option-p/--old-port.PGPORTNEWβ the new cluster port number; that's option-P/--new-port.PGSOCKETDIRβ directory to use for postmaster sockets during upgrade; that's option-s/--socketdir.PGUSERβ cluster's install user name; that's option-U/--username.
π NOTES π
pg_upgrade creates various working files, like schema dumps, stored inside pg_upgrade_output.d in the directory of the new cluster. Each run creates a new subdirectory named with a timestamp formatted as per ISO 8601 (%Y%m%dT%H%M%S), and all its generated files get stored in there. pg_upgrade_output.d and everything in it gets removed automatically if pg_upgrade completes successfully β but if things go sideways, the files in there may provide useful debugging info. π
pg_upgrade launches short-lived postmasters in the old and new data directories. Temporary Unix socket files for talking to those postmasters are, by default, made in the current working directory. Sometimes the path name for the current directory is too long to be a valid socket name β in that case you can use the -s option to put the socket files in some directory with a shorter path name. For security, please be sure that directory is not readable or writable by any other users. (This is not supported on Windows. πͺ)
All failure, rebuild, and reindex cases will be reported by pg_upgrade if they affect your installation; post-upgrade scripts to rebuild tables and indexes get generated automatically. If you're trying to automate the upgrade of many clusters, you should find that clusters with identical database schemas require the same post-upgrade steps for all cluster upgrades β this is because the post-upgrade steps are based on the database schemas, not user data. π§
For deployment testing, create a schema-only copy of the old cluster, insert dummy data, and upgrade that.
pg_upgrade does not support upgrading of databases containing table columns using these reg* OID-referencing system data types:
regcollation
regconfig
regdictionary
regnamespace
regoper
regoperator
regproc
regprocedure
(regclass, regrole, and regtype can be upgraded. those are the lucky ones π«)
If you want to use link mode and you do not want your old cluster to be modified when the new cluster is started, consider using the clone mode. If that's not available, make a copy of the old cluster and upgrade that in link mode. To make a valid copy of the old cluster, use rsync to create a dirty copy of the old cluster while the server is running, then shut down the old server and run rsync --checksum again to update the copy with any changes to make it consistent. (--checksum is necessary because rsync only has file modification-time granularity of one second. β±οΈ) You might want to exclude some files, like postmaster.pid, as documented in Section 25.3.4. If your file system supports file system snapshots or copy-on-write file copies, you can use that to make a backup of the old cluster and tablespaces β though the snapshot and copies must be created simultaneously or while the database server is down.
π¦ SEE ALSO π¦
initdb(1), pg_ctl(1), pg_dump(1), postgres(1)
and that's the whole page bestie, you ate that π«Ά this one's straight from the PostgreSQL 18.6 manual, dated 2026, and it goes by the name PG_UPGRADE(1). now go upgrade something responsibly, mwah π β¨π
π¦ where this page comes from
- opensuse-leap 16.0: postgresql18-server 18.6-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql18-server 18.6-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql18-server 18.6-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql18-server 18.6-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms