8

I want to restore a database of postgreSQL, but before do it i need to empty the restore target database.

Is there an option of psql to do it ?

Now i use a command line as the following :

psql -U postgres db_test < testdb.sql
aleroot
  • 3,160
  • 5
  • 28
  • 37

2 Answers2

12

There are two options here - if your backup is plain text then you add the -c option to pg_dump - ie

pg_dump -c mydb > mydb.sql

Otherwise if your using -Fc or -Ft on pg_dump then you use the -c flag on pg_restore

pg_dump -Ft -b mydb > db.tar

pg_restore -c -d newdb db.tar

Geraint Jones
  • 2,483
  • 16
  • 19
1

Assuming you're talking about restoring from a pg_dump backup the answer is "it depends on how the backup was made", but typically yes: You must empty the database before restoring the backup.

The fastest way to empty out a database in Postgres is to drop and re-create the database (you'll probably need superuser privileges for that), otherwise you have to manually drop each table and any stored procedures you may have (CASCADE is your friend here).

voretaq7
  • 79,345
  • 17
  • 128
  • 213
  • is there a way of do a backup with pg_dump that when i restore it, first erase the destination db and then restore the data ? Thanks – aleroot Aug 31 '10 at 20:44
  • I use `--clean` and `--if-exists` arguments on *both* `pg_dump` and `pg_restore` which works really well, but I'm also using the `--format=c` (custom) output format rather than a dump SQL statements. I'm also using PostgreSQL 12 and this question/answer is a bit older than that! – Neil C. Obremski Oct 17 '21 at 20:24