Databases

Back up and restore a PostgreSQL database

Save a whole database to a .sql file with pg_dump, then load it back with psql.

Fill these in once
  1. Back up a database to a file
    Terminal
    pg_dump -h localhost -U postgres -d myapp_dev -f myapp_dev.sql
  2. Restore it into a new database
    Terminal
    createdb -h localhost -U postgres myapp_dev_restored
    psql -h localhost -U postgres -d myapp_dev_restored -f myapp_dev.sql

Check it worked

  1. List the tables in the restored copy
    Terminal
    psql -h localhost -U postgres -d myapp_dev_restored -c "\dt"
  1. Back up a database to a file
    Terminal · Ubuntu / Debian
    pg_dump -h localhost -U postgres -d myapp_dev -f myapp_dev.sql
  2. Restore it into a new database
    Terminal · Ubuntu / Debian
    createdb -h localhost -U postgres myapp_dev_restored
    psql -h localhost -U postgres -d myapp_dev_restored -f myapp_dev.sql

Check it worked

  1. List the tables in the restored copy
    Terminal · Ubuntu / Debian
    psql -h localhost -U postgres -d myapp_dev_restored -c "\dt"
  1. Back up a database to a file
    PowerShell
    pg_dump -h localhost -U postgres -d myapp_dev -f myapp_dev.sql
  2. Restore it into a new database
    PowerShell
    createdb -h localhost -U postgres myapp_dev_restored
    psql -h localhost -U postgres -d myapp_dev_restored -f myapp_dev.sql

Check it worked

  1. List the tables in the restored copy
    PowerShell
    psql -h localhost -U postgres -d myapp_dev_restored -c "\dt"