
This is a ‘how to’ doc which only gives example commands, how it is done actually is solely dependent on the person doing it and specific use cases.
First, a disclaimer. This post provides a general guide on how to backup a Postgres Database Table. The examples provided do not refer to any specific table or database. If you are trying to backup a specific table, you should also backup tables which refer to the original tables. As Postgres is a relational database, there will always be references between a number of tables.
This is a ‘how to’ doc which only gives example commands, how it is done actually is solely dependent on the person doing it and specific use cases. Always maintain the integrity of the data you are trying to backup. Backing up the entire database is always a safe option, but when backing up specific tables one needs to be careful.
SQL-dump/pg_dump:
The idea behind the SQL-dump method 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 in at the time of the dump. PostgreSQL provides the utility program pg_dump for this purpose.
pg_dump is an effective and comprehensive tool to take Postgres database backups and use the backups to restore the postgres database. It is however not restricted to Database only. We can use pg_dump to backup tables and then use that to restore individual tables as well. Using pg_dump you can backup the local database and restore it on a remote database.
How to Backup Postgres Database :
How to Restore Postgres Database
Restore a Postgres table :
$ /opt/msys/3rdParty/bin/psql -U ecuser -f ms_table.sql pe
The above command will install the table that was backed up in ms_table.sql file to the ‘pe’ database. Make sure that this table does not already exist, or you will see a bunch of ‘already exists’ errors. This command creates the table and exports all the data to the newly created table.
Restore a postgres Database :
$ /opt/msys/3rdParty/bin/psql -U ecuser -d pe -f pe_dump.sql
Similar to restoring the table, we can use the above command to restore the complete database. Here we are restoring the ‘pe’ database using the file pe_dump.sql which we had created while backing up the database in the Backup section above.
Restore all Databases :
$ /opt/msys/3rdParty/bin/psql -u ecuser -f all_dump.sql
Restore all the databases using the above command. ‘all_dump.sql’ was the file that was created using pg_dumpall. The above command will give us all the Postgres databases in the exact state that they were in when a dump was taken from the original database server.