Chapter 7. Backup and Restore

PostgreSQL databases should be backed up regularly. While the procedure is essentially simple, it is important to have a basic understanding of the underlying techniques and assumptions.

There are two fundamentally different approaches to backing up PostgreSQL data:

SQL Dump

The idea behind an SQL dump is to generate a text file with SQL commands that, when fed back to the server, will recreate the database in the same state as it was at the time of the dump. PostgreSQL provides the utility program pg_dump for this purpose. The basic usage of this command is:
pg_dump dbname > outfile
The pg_dump writes its results to the standard output. (See the section on pg_dump for details.)

pg_dump is a regular PostgreSQL client application. This means that you can do this backup procedure from any remote host that has access to the database. But pg_dump does not operate with special permissions: you must have read access to all tables that you want to back up, so in practice you almost always have to be a database superuser.

To specify which database server pg_dump should contact, use the command line options -h host and -p port. The default host is the local host or whatever your PGHOST environment variable specifies. Similarly, the default port is indicated by the PGPORT environment variable or, failing that, by the compiled-in default.

As with any other PostgreSQL client application, pg_dump will by default connect with the database user name that is equal to the current Linux user name. To override this, either specify the -U option or set the environment variable PGUSER. Remember that pg_dump connections are subject to the normal client authentication mechanisms.

Dumps created by pg_dump are internally consistent, so updates to the database while pg_dump is running will not be in the dump. pg_dump does not block other operations on the database while it is working. (Exceptions are those operations that need to operate with an exclusive lock, such as VACUUM FULL.)

Important

When your database schema relies on OIDs (for instance as foreign keys) you must instruct pg_dump to dump the OIDs as well. To do this, use the -o command line option. "Large objects" are not dumped by default, either. See pg_dump's command reference page if you use large objects.