Back up and restore with PostgreSQL tools

PostgreSQL 19.0

Create a logical backup of one database and prove you can restore it to a separate database.

On this page

Create a custom-format archive

Use pg_dump with -Fc. After Setup, run this from the OS terminal. The source account needs read access to the objects and data being backed up. The pg_dump client must be at least as new as the server’s major version. Keep backup files private because they contain database contents.

pg_dump -h localhost -p 5432 -U postgres -Fc -f learning_db.dump learning_db
pg_restore --list learning_db.dump
pg_dump -h localhost -p 5432 -U postgres -Fc -f learning_db.dump learning_db
Connect as postgres on localhost, read learning_db, and save a custom-format archive to learning_db.dump. The -f flag sets the output filename.
pg_restore --list learning_db.dump
List the objects in the archive without restoring them.

Restore into a fresh database

Create an empty test database with an account allowed to create databases. If another account owns the test database, connect as that account to restore. For this restore check, --no-owner and --no-privileges skip restoring the original owners and grants. Compare key table counts and check an app read. Plan a separate backup of roles and other cluster-wide objects, and use your host’s point-in-time recovery tools if you need replay to a particular time.

createdb -h localhost -p 5432 -U postgres learning_db_restore
pg_restore -h localhost -p 5432 -U postgres -d learning_db_restore --exit-on-error --no-owner --no-privileges learning_db.dump
psql -h localhost -p 5432 -U postgres -d learning_db_restore -c "SELECT count(*) FROM students;"
createdb … learning_db_restore
Creates the empty target database as postgres.
pg_restore … -d learning_db_restore --exit-on-error
Restores learning_db.dump into the database selected by -d and stops on the first error.
psql … -c "SELECT count(*) FROM students;"
Runs the quoted SQL once and exits. Compare the student row count with the source database.

Official references