Showing posts with label Restore Postgres. Show all posts
Showing posts with label Restore Postgres. Show all posts

Monday, 28 November 2011

How to Create Database dump Backup and restore postgresql

To create dump file as a backup from postgresql follow the simple commands below:
pg_dump is an effective tool to backup postgres database. It creates a *.sql file with CREATE TABLE, ALTER TABLE, and COPY SQL statements of source database. To restore these dumps psql command is enough.
 
1: login to your server through ssh
and run the commands:

2: pg_dump -U {user-name} {source_db} -f > {dumpfilename.sql}
In my case it will be 
    pg_dump -U shahmeer firstdb > firstdb.sql

Backup all postgres databases
To backup all databases, list out all the available databases;
login as postgres /psql user:
# su - postgres
#psql -l
will show you list of the databases;
\q
run the command to backup all the databases:
#pg_dumpall > alldbs.sql
now as the backup completed you have to verify the backup;
# grep "^[\]connect" alldbs.sql
\connect db1
\connect db2
\connect db3...


3: Backup a single table from specific database:
# pg_dump --table contacts -U shahmeer -d firstdb -f conatactstable.sql

How To Restore Postgres Database;

1: Restore postgres database

# psql -U shahmeer firstdb.sql < newdb
if you are going to restore the local database on the remote server then use the below command
#pg_dump firstdb.sql | psql -h hostname dbname

3: Restore All the postgres databases

#su postgres
#psql -f alldb.sql
4: Restore a single postgres table
#psql -f contacts.sql newdb
where new db is the database name and contacts.sql is a dump of table contacts

5:To create a dump of two tables in a single command:

# pg_dump -t table1, -t table2 -U firstdb > 2tables.sql

Thats it, if you have any query regarding this post or if facing any issue please comments here.