Tech Tips: How do I Backup and Restore the Postgres Database?
Karan Singh
19 Jun 2013
1 min read

Key Takeaways
PostgreSQL backups can target a single table, a single database, or all databases depending on your needs.
pg_dumpcreates a SQL text file containing DDL and data needed to recreate the target table or database.pg_dumpallbacks up every database on the Postgres instance.Restoring is done with
psql, which executes the SQL dump back into the target database.Table-level restores require ensuring the table does not already exist to avoid conflicts.
When backing up individual tables, be mindful of relational dependencies.
Dumps can be taken from local and restored to remote Postgres instances.
Backups include
CREATE,ALTER, andCOPYcommands depending on what is being exported.Proper backup strategy depends on understanding table relationships, schema usage, and deployment environments.
Always ensure data integrity by taking backups that include referenced tables when necessary.
Q&A Highlights
What does pg_dump actually do?
pg_dumpgenerates a text-based SQL file containing the full set of commands needed to recreate a table or database exactly as it existed at the time of backup.Can I back up just one table instead of a full database?
Yes. Use
pg_dump --table TABLENAMEto export a specific table. If tables with the same name exist across schemas, use--schemato specify the correct one.Should I worry about related tables when backing up a single table?
Absolutely. PostgreSQL is relational, so other tables might reference the one you’re backing up. If you restore only one table without related ones, you may break referential integrity.
How do I back up a full database?
Run a command like:
pg_dump -U <user> <database> -f <output.sql>This exports all tables, schema definitions, indexes, and data for that database.
What does pg_dumpall do?
pg_dumpallbacks up every database on the server into a single SQL file. It’s useful when migrating or snapshotting an entire Postgres instance.Can I restore a table into an existing database?
Yes. Use
psql -U <user> -f <file.sql> <database>.But ensure the table does not already exist — otherwise you’ll get “already exists” errors during restore.
What happens during a full database restore?
The restore file runs:
CREATE TABLEALTER TABLECOPY(for table data)
bringing the database back to its exact state at dump time.
Can I restore to a different server than the one I backed up from?
Yes. Dumps are portable. You can take a backup locally and restore it to a remote Postgres instance, provided the versions are compatible.
Does pg_dump affect the running database?
No. It works via SQL queries and does not lock the entire database. It safely captures a consistent snapshot.
How do I restore all databases from a pg_dumpall file?
Use:
psql -U <user> -f all_dump.sqlThis recreates every database found in the dump.



