Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save farhad0085/4150cfc1ad68f8019fa2d5a7b99845b4 to your computer and use it in GitHub Desktop.
Save farhad0085/4150cfc1ad68f8019fa2d5a7b99845b4 to your computer and use it in GitHub Desktop.
Postgresql database dump and restore

Dump Your PostgreSQL Database

Login to your server and run this command. This will dump your database in compressed format in current directory.

pg_dump database_name -U db_username -h localhost -F c > db_dump_compressed.sql

It will ask you for db_username's password. After taking some time, it'll save the db dump in a file called db_dump_compressed.sql

If you don't want it to be compressed, just remove -F c from the above command.

pg_dump database_name -U db_username -h localhost > db_dump.sql

You can now use this dump as the backup for your database.

Restore Your PostgreSQL Dump

Step 1

If you want to use the current localhost database, you must drop it first:

psql template1 -c 'drop database database_name;'

Step 2

Create a new database on the localhost:

psql template1 -c 'create database database_name with owner your_user_name;

Step 3

And write your dump into the database:

psql database_name < database_name_20160527.sql

In windows, go to postgres bin folder and the run this command also add username after the command. like this:

./psql.exe database_name < db_dump.sql postgres

That's all! You now have the exact copy of production database available on your machine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment