Sub topic 3
Dumping a single database with pg_dump
This chapter assumes you can use psql, work at a Linux command line, and know what roles, databases, and transactions are. It builds on the previous chapter's distinction between logical and physical backups. Here you will use pg_dump, the main logical backup tool, to back up one database.
What pg_dump does
pg_dump is a client program that connects to a running server like any other client and reads a database. It writes out the SQL commands, or an equivalent archive, needed to recreate that database's objects and data. Because it only reads through a normal connection, it needs no access to the server's data directory and can run from another machine.
A dump covers exactly one database. It does not include:
- Roles. Ownership and privileges appear in the dump, but the roles themselves do not.
- Tablespace definitions.
- Other databases in the cluster.
The next chapters cover roles and cluster-wide objects with pg_dumpall.
How a dump stays consistent
A dump can take minutes or hours while other sessions keep writing. pg_dump handles this with a single snapshot. It opens a transaction at the REPEATABLE READ isolation level, read-only. Every table it reads is then seen as of the same moment, so foreign keys in the dump match.
It also takes an ACCESS SHARE lock on every table it is going to dump. That lock does not block ordinary reads and writes. It does conflict with ACCESS EXCLUSIVE locks, which are taken by DROP TABLE, TRUNCATE, VACUUM FULL, and many ALTER TABLE forms. If someone runs one of those while a dump is in progress, one of two things happens:
- The DDL waits for the dump to finish, and sessions queued behind it wait too.
- The dump waits for the DDL, if the DDL got its lock first.
A long dump has a cost on the server. Its snapshot stays open for the whole run, so vacuum cannot remove row versions that were still visible when the dump started. On a busy database, a multi-hour dump can cause table bloat.
A first dump
The custom format is a good default for a single database. It is compressed and can be restored selectively with pg_restore.
pg_dump -h localhost -U postgres -Fc -f mydb.dump mydbThe options are:
-hand-Uset the host and user.-Fcselects the custom format.-fnames the output file.- The last argument,
mydb, is the database name.
If you leave out -f, pg_dump writes to standard output. Without -F, the format is plain SQL. Plain SQL to stdout is convenient for piping, but it gives you no selective restore and no compression unless you add it yourself.
Connecting without a prompt
For unattended runs, pg_dump must not stop to ask for a password. The usual choices are:
- A
~/.pgpassfile with permissions0600. - The
PGPASSFILEenvironment variable pointing to such a file. - Peer or certificate authentication.
Avoid putting the password on the command line, where other users can see it in the process list.
Checking the result
Check the exit status. A non-zero status means the dump is incomplete and must not be treated as a backup. Then confirm that the file is readable:
pg_dump -h localhost -U postgres -Fc -f mydb.dump mydb || echo "dump failed" >&2
pg_restore --list mydb.dump | head -n 20pg_restore --list prints the archive's table of contents. This confirms that the file is a valid archive. It does not prove that the data restores correctly. Only a full test restore proves that, and a later chapter covers it.
Choosing what goes into the dump
By default you get every schema and table in the database. These options narrow the selection.
| Option | Effect |
|---|---|
| `-n schema` | Dump only the matching schemas. Repeatable. |
| `-N schema` | Exclude the matching schemas. |
| `-t table` | Dump only the matching tables, views, sequences, and foreign tables. Repeatable. |
| `-T table` | Exclude the matching tables. |
| `-s` / `--schema-only` | Definitions only, no rows. |
| `-a` / `--data-only` | Rows only, no definitions. |
| `--exclude-table-data=pattern` | Keep the table definition but skip its rows. |
Patterns follow psql rules, so -t 'sales.*' selects every object in the sales schema. Quote patterns so the shell does not expand them.
pg_dump -U postgres -Fc -n sales -T 'sales.audit_log' -f sales.dump mydbGotchas when selecting objects
-tdoes not follow dependencies. If the selected table uses a sequence, a type, or a view, that object is not included automatically. Restoring such a dump into an empty database can fail. Dump whole schemas with-nwhen you need a self-contained result.- Large objects, the binary objects stored through the
lo_*functions, are included in a whole-database dump. They are left out when you use-n,-t, or--schema-only, unless you add-b(--large-objects). Check whether your application uses them withSELECT count(*) FROM pg_largeobject_metadata;. --data-onlyproduces a dump that expects the tables to exist already. Use it only when you manage the schema separately, for example with migrations.
Options that shape the restore
Some options change the SQL or archive contents so that the later restore behaves differently.
--no-owneromits the commands that set object ownership. This is useful when you restore as a different user. Restoring withpg_restore --no-ownerhas the same effect for archives.--no-privileges(-x) omitsGRANTandREVOKEcommands.-C/--createincludesCREATE DATABASEand a connect command. It is mainly useful with plain SQL, where the restore script creates the database itself.-c/--cleanaddsDROPcommands before theCREATEcommands, and--if-existsstops those drops from failing when an object is absent. Use this pair carefully, because it makes the restore destructive on the target.--no-comments,--no-tablespaces, and--no-security-labelsleave out other metadata.--no-tablespaceshelps when the target server has a different tablespace layout.
For the dump in the custom format, --create and --clean are normally decided at restore time by pg_restore, not at dump time.
Compression and size
The custom format compresses by default. Use -Z to set the level, from 0 (none) to 9 (maximum), and from PostgreSQL 16 you can also name an algorithm, such as -Z zstd:5. Higher levels cost more CPU on the machine that runs pg_dump. For large databases, a moderate level is usually the better trade-off than the maximum.
pg_dump -U postgres -Fc -Z 6 -f mydb.dump mydbA dump is usually much smaller than the database itself, because indexes are stored only as CREATE INDEX commands and are rebuilt during the restore. The restore therefore takes longer than the file size suggests: it must reload the rows and rebuild every index.
Version compatibility
pg_dump can dump servers older than itself, and it is the recommended practice to run a pg_dump at least as new as the server. A pg_dump older than the server refuses to run. When you plan to upgrade, use the newer pg_dump against the old server, and restore with the matching newer pg_restore.
Dumps can generally be restored into the same or a newer major version. Restoring into an older major version is not supported.
What pg_dump cannot do
- It restores the database as of the snapshot start. You cannot choose a point in time within a dump. Point-in-time recovery needs a base backup and archived WAL, covered later in this tutorial.
- Your recovery point is the time of the last dump. If you dump nightly, you can lose up to a day of changes.
- It cannot dump a standby that is replaying conflicting changes, without the risk of cancelled queries. On a hot standby, a long dump may be cancelled by recovery conflicts unless you tune the standby's delay settings.
Common errors
pg_dump: error: query failed: ERROR: permission denied for table ...means the connecting role cannot read some object. Use a role with read access to everything, such as a superuser or a member ofpg_read_all_data(PostgreSQL 14 and later).pg_dump: error: aborting because of server version mismatchmeans yourpg_dumpis older than the server. Install a newer client.FATAL: database "mydb" does not existusually means a typo, or that you connected to the wrong host or port.- A dump that seems to hang is often waiting for a table lock held by a long transaction or a pending DDL statement. Use
--lock-wait-timeout=30sso the dump fails fast instead of stalling the system.
Exercise
Your team runs pg_dump -Fc -t orders -f orders.dump shop and later finds that restoring orders.dump into an empty database fails because a sequence and a type used by the table are missing. Why did this happen, and what is a more reliable way to take the dump?
Show answer
The -t option dumps only the named table and does not follow dependencies, so the sequence and type that orders uses were not included. A more reliable way is to dump the whole schema that holds these objects, for example pg_dump -Fc -n public -f shop_public.dump shop. If you need only one table's rows, restore them into a database where the schema already exists.