How to Backup and Restore a PostgreSQL Database with pg_dump & psql
Export compressed SQL dump archives and restore them cleanly to local or remote database instances.
# Backup:
pg_dump -U postgres -d mydb -Fc -f mydb_backup.dump
# Restore:
pg_restore -U postgres -d mydb --clean --if-exists mydb_backup.dumpStep-by-Step Query Breakdown
pg_dump -U postgres -h localhost -p 5432 -d production_db -Fc -f backup_2026.dump-Fc produces a compressed custom format archive that supports parallel multi-threaded restores and selective table extraction.
pg_dump -U postgres -d production_db > backup.sqlCreates a human-readable SQL text script that can be inspected with any text editor.
pg_restore -U postgres -d dev_db --clean --if-exists -j 4 backup_2026.dump--clean drops existing database objects before recreating them. -j 4 uses 4 parallel CPU jobs for blazing fast restores.
psql -U postgres -d dev_db -f backup.sqlExecutes the SQL script line-by-line using psql.
Critical SQL Pitfalls & Precautions
- β’Do not use "psql" to restore custom format (.dump) files. Always use "pg_restore" for -Fc archives and "psql" for plain text .sql files.
PostgreSQL Backup & Restore (pg_dump) - Frequently Asked Questions
Common questions about transactional safety, indexing, and engine compatibility.
Use the "-t" flag: "pg_dump -U postgres -d mydb -t users -Fc -f users.dump".
Related SQL Query Guides
Browse All SQL RecipesIdentify rows with duplicate column values using GROUP BY and HAVING count(*) > 1, and safely remove duplicates using ROW_NUMBER() CTEs.
Compare row-by-row logging (DELETE), fast table emptying with auto-increment reset (TRUNCATE), and complete table removal (DROP).
Atomically insert a new row or update an existing row if a unique constraint or primary key conflict is encountered.
Compute cumulative running totals over time or partitioned groups using SUM() OVER (ORDER BY ...).
Build a production database index on a table with millions of rows without locking out live INSERT, UPDATE, or DELETE operations.
Update values in one table based on matching columns or aggregations in a secondary table.