I want to restore the database with a different schema

A quick and dirty way:

1) rename default schema:

alter schema public rename to public_save;

2) create new schema as default schema:

create schema public;

3) restore data

pg_restore -f pub.backup db_temp [and whatever other options]

4) rename schemas according to need:

alter schema public rename to temp_schema;
alter schema public_save rename to public;

There is a simple solution:

  • Create your backup dump in plain SQL format (format "p" using the parameter --format=p or -F p)
  • Edit your pub.backup.sql dump with your favorite editor and add the following two lines at the top of your file:

create schema myschema;

SET search_path TO myschema;

Now you can restore your backup dump with the command

psql -f pub.backup.sql

The set search_path to <schema> command will set myschema as the default, so that new tables and other objects are created in this schema, independently of the "default" schema where they lived before.


There's no way in pg_restore itself. What you can do is use pg_restore to generate SQL output, and then send this through for example a sed script to change it. You need to be careful about how you write that sed script though, so it doesn't match and change things inside your data.


Probably the easiest method would be to simply rename the schema after restore, ie with the following SQL:

ALTER SCHEMA my_schema RENAME TO temp_schema

I believe that because you're using the compressed archive format for the output of pg_dump you can't alter it before restoring. The option would be to use the default output and do a search and replace on the schema name, but that would be risky and could perhaps cause data to be corrupted if you were not careful.