Linux "pg_restore" Command Line Options and Examples
restore a PostgreSQL database from an archive file created by pg_dump

pg_restore is a utility for restoring a PostgreSQL database from an archive created by pg_dump(1) in one of the non-plain-text formats. It will issue the commands necessary to reconstruct the database to the state it was in at the time it was saved.


Usage:

pg_restore [connection-option...] [option...] [filename]






Command Line Options:

--data-only
Restore only the data, not the schema (data definitions). Table data, large objects, and sequence valuesare restored, if present in the archive.This option is similar to, but for historical reasons not identical to, specifying --section=data.
pg_restore --data-only ...
--clean
Clean (drop) database objects before recreating them. (Unless --if-exists is used, this might generatesome harmless error messages, if any objects were not present in the destination database.)
pg_restore --clean ...
--create
Create the database before restoring into it. If --clean is also specified, drop and recreate the targetdatabase before connecting to it.When this option is used, the database named with -d is used only to issue the initial DROP DATABASE andCREATE DATABASE commands. All data is restored into the database name that appears in the archive.
pg_restore --create ...
--dbname
Connect to database dbname and restore directly into the database.
pg_restore --dbname ...
--exit-on-error
Exit if an error is encountered while sending SQL commands to the database. The default is to continue andto display a count of errors at the end of the restoration.
pg_restore --exit-on-error ...
--file
Specify output file for generated script, or for the listing when used with -l. Default is the standardoutput.
pg_restore --file ...
--format
Specify format of the archive. It is not necessary to specify the format, since pg_restore will determinethe format automatically. If specified, it can be one of the following:ccustomThe archive is in the custom format of pg_dump.ddirectoryThe archive is a directory archive.ttarThe archive is a tar archive.
pg_restore --format ...
--index
Restore definition of named index only. Multiple indexes may be specified with multiple -I switches.
pg_restore --index ...
--jobs
Run the most time-consuming parts of pg_restore — those which load data, create indexes, or createconstraints — using multiple concurrent jobs. This option can dramatically reduce the time to restore alarge database to a server running on a multiprocessor machine.Each job is one process or one thread, depending on the operating system, and uses a separate connectionto the server.The optimal value for this option depends on the hardware setup of the server, of the client, and of thenetwork. Factors include the number of CPU cores and the disk setup. A good place to start is the numberof CPU cores on the server, but values larger than that can also lead to faster restore times in manycases. Of course, values that are too high will lead to decreased performance because of thrashing.Only the custom and directory archive formats are supported with this option. The input must be a regularfile or directory (not, for example, a pipe). This option is ignored when emitting a script rather thanconnecting directly to a database server. Also, multiple jobs cannot be used together with the option
pg_restore --jobs ...
--list
List the table of contents of the archive. The output of this operation can be used as input to the -Loption. Note that if filtering switches such as -n or -t are used with -l, they will restrict the itemslisted.
pg_restore --list ...
--use-list
Restore only those archive elements that are listed in list-file, and restore them in the order theyappear in the file. Note that if filtering switches such as -n or -t are used with -L, they will furtherrestrict the items restored.list-file is normally created by editing the output of a previous -l operation. Lines can be moved orremoved, and can also be commented out by placing a semicolon (;) at the start of the line. See below forexamples.
pg_restore --use-list ...
--schema
Restore only objects that are in the named schema. Multiple schemas may be specified with multiple -nswitches. This can be combined with the -t option to restore just a specific table.
pg_restore --schema ...
--exclude-schema
Do not restore objects that are in the named schema. Multiple schemas to be excluded may be specified withmultiple -N switches.When both -n and -N are given for the same schema name, the -N switch wins and the schema is excluded.
pg_restore --exclude-schema ...
--no-owner
Do not output commands to set ownership of objects to match the original database. By default, pg_restoreissues ALTER OWNER or SET SESSION AUTHORIZATION statements to set ownership of created schema elements.These statements will fail unless the initial connection to the database is made by a superuser (or thesame user that owns all of the objects in the script). With -O, any user name can be used for the initialconnection, and this user will own all the created objects.
pg_restore --no-owner ...
--function=function-name(argtype
Restore the named function only. Be careful to spell the function name and arguments exactly as theyappear in the dump file's table of contents. Multiple functions may be specified with multiple -Pswitches.
pg_restore --function=function-name(argtype ...
--no-reconnect
This option is obsolete but still accepted for backwards compatibility.
pg_restore --no-reconnect ...
--schema-only
Restore only the schema (data definitions), not data, to the extent that schema entries are present in thearchive.This option is the inverse of --data-only. It is similar to, but for historical reasons not identical to,specifying --section=pre-data --section=post-data.(Do not confuse this with the --schema option, which uses the word “schema” in a different meaning.)
pg_restore --schema-only ...
--superuser
Specify the superuser user name to use when disabling triggers. This is relevant only if
pg_restore --superuser ...
--table
Restore definition and/or data of only the named table. For this purpose, “table” includes views,materialized views, sequences, and foreign tables. Multiple tables can be selected by writing multiple -tswitches. This option can be combined with the -n option to specify table(s) in a particular schema.NoteWhen -t is specified, pg_restore makes no attempt to restore any other database objects that theselected table(s) might depend upon. Therefore, there is no guarantee that a specific-table restoreinto a clean database will succeed.NoteThis flag does not behave identically to the -t flag of pg_dump. There is not currently any provisionfor wild-card matching in pg_restore, nor can you include a schema name within its -t.NoteIn versions prior to PostgreSQL 9.6, this flag matched only tables, not any other type of relation.
pg_restore --table ...
--trigger
Restore named trigger only. Multiple triggers may be specified with multiple -T switches.
pg_restore --trigger ...
--verbose
Specifies verbose mode.
pg_restore --verbose ...
--version
Print the pg_restore version and exit.
pg_restore --version ...
--no-acl
Prevent restoration of access privileges (grant/revoke commands).
pg_restore --no-acl ...
--single-transaction
Execute the restore as a single transaction (that is, wrap the emitted commands in BEGIN/COMMIT). Thisensures that either all the commands complete successfully, or no changes are applied. This option implies
pg_restore --single-transaction ...
--disable-triggers
This option is relevant only when performing a data-only restore. It instructs pg_restore to executecommands to temporarily disable triggers on the target tables while the data is reloaded. Use this if youhave referential integrity checks or other triggers on the tables that you do not want to invoke duringdata reload.Presently, the commands emitted for --disable-triggers must be done as superuser. So you should alsospecify a superuser name with -S or, preferably, run pg_restore as a PostgreSQL superuser.
pg_restore --disable-triggers ...
--enable-row-security
This option is relevant only when restoring the contents of a table which has row security. By default,pg_restore will set row_security to off, to ensure that all data is restored in to the table. If the userdoes not have sufficient privileges to bypass row security, then an error is thrown. This parameterinstructs pg_restore to set row_security to on instead, allowing the user to attempt to restore thecontents of the table with row security enabled. This might still fail if the user does not have the rightto insert the rows from the dump into the table.Note that this option currently also requires the dump be in INSERT format, as COPY FROM does not supportrow security.
pg_restore --enable-row-security ...
--if-exists
Use conditional commands (i.e. add an IF EXISTS clause) when cleaning database objects. This option is notvalid unless --clean is also specified.
pg_restore --if-exists ...
--no-data-for-failed-tables
By default, table data is restored even if the creation command for the table failed (e.g., because italready exists). With this option, data for such a table is skipped. This behavior is useful if the targetdatabase already contains the desired table contents. For example, auxiliary tables for PostgreSQLextensions such as PostGIS might already be loaded in the target database; specifying this option preventsduplicate or obsolete data from being loaded into them.This option is effective only when restoring directly into a database, not when producing SQL scriptoutput.
pg_restore --no-data-for-failed-tables ...
--no-publications
Do not output commands to restore publications, even if the archive contains them.
pg_restore --no-publications ...
--no-security-labels
Do not output commands to restore security labels, even if the archive contains them.
pg_restore --no-security-labels ...
--no-subscriptions
Do not output commands to restore subscriptions, even if the archive contains them.
pg_restore --no-subscriptions ...
--no-tablespaces
Do not output commands to select tablespaces. With this option, all objects will be created in whichevertablespace is the default during restore.
pg_restore --no-tablespaces ...
--section
Only restore the named section. The section name can be pre-data, data, or post-data. This option can bespecified more than once to select multiple sections. The default is to restore all sections.The data section contains actual table data as well as large-object definitions. Post-data items consistof definitions of indexes, triggers, rules and constraints other than validated check constraints.Pre-data items consist of all other data definition items.
pg_restore --section ...
--strict-names
Require that each schema (-n/--schema) and table (-t/--table) qualifier match at least one schema/table inthe backup file.
pg_restore --strict-names ...
--use-set-session-authorization
Output SQL-standard SET SESSION AUTHORIZATION commands instead of ALTER OWNER commands to determine objectownership. This makes the dump more standards-compatible, but depending on the history of the objects inthe dump, might not restore properly.
pg_restore --use-set-session-authorization ...
--help
Show help about pg_restore command line arguments, and exit.pg_restore also accepts the following command line arguments for connection parameters:
pg_restore --help ...
--host
Specifies the host name of the machine on which the server is running. If the value begins with a slash,it is used as the directory for the Unix domain socket. The default is taken from the PGHOST environmentvariable, if set, else a Unix domain socket connection is attempted.
pg_restore --host ...
--port
Specifies the TCP port or local Unix domain socket file extension on which the server is listening forconnections. Defaults to the PGPORT environment variable, if set, or a compiled-in default.
pg_restore --port ...
--username
User name to connect as.
pg_restore --username ...
--no-password
Never issue a password prompt. If the server requires password authentication and a password is notavailable by other means such as a .pgpass file, the connection attempt will fail. This option can beuseful in batch jobs and scripts where no user is present to enter a password.
pg_restore --no-password ...
--password
Force pg_restore to prompt for a password before connecting to a database.This option is never essential, since pg_restore will automatically prompt for a password if the serverdemands password authentication. However, pg_restore will waste a connection attempt finding out that theserver wants a password. In some cases it is worth typing -W to avoid the extra connection attempt.
pg_restore --password ...
--role
Specifies a role name to be used to perform the restore. This option causes pg_restore to issue a SET ROLErolename command after connecting to the database. It is useful when the authenticated user (specified by
pg_restore --role ...
-U)
installations have a policy against logging in directly as a superuser, and use of this option allowsrestores to be performed without violating the policy.ENVIRONMENTPGHOSTPGOPTIONSPGPORTPGUSERDefault connection parametersThis utility, like most other PostgreSQL utilities, also uses the environment variables supported by libpq(see Section 33.14). However, it does not read PGDATABASE when a database name is not supplied.DIAGNOSTICSWhen a direct database connection is specified using the -d option, pg_restore internally executes SQLstatements. If you have problems running pg_restore, make sure you are able to select information from thedatabase using, for example, psql(1). Also, any default connection settings and environment variables used bythe libpq front-end library will apply.NOTESIf your installation has any local additions to the template1 database, be careful to load the output ofpg_restore into a truly empty database; otherwise you are likely to get errors due to duplicate definitions ofthe added objects. To make an empty database without any local additions, copy from template0 not template1,for example:CREATE DATABASE foo WITH TEMPLATE template0;The limitations of pg_restore are detailed below.· When restoring data to a pre-existing table and the option --disable-triggers is used, pg_restore emitscommands to disable triggers on user tables before inserting the data, then emits commands to re-enablethem after the data has been inserted. If the restore is stopped in the middle, the system catalogs mightbe left in the wrong state.· pg_restore cannot restore large objects selectively; for instance, only those for a specific table. If anarchive contains large objects, then all large objects will be restored, or none of them if they areexcluded via -L, -t, or other options.See also the pg_dump(1) documentation for details on limitations of pg_dump.Once restored, it is wise to run ANALYZE on each restored table so the optimizer has useful statistics; seeSection 24.1.3 and Section 24.1.6 for more information.EXAMPLESAssume we have dumped a database called mydb into a custom-format dump file:$ pg_dump -Fc mydb > db.dumpTo drop the database and recreate it from the dump:$ dropdb mydb$ pg_restore -C -d postgres db.dumpThe database named in the -d switch can be any database existing in the cluster; pg_restore only uses it toissue the CREATE DATABASE command for mydb. With -C, data is always restored into the database name thatappears in the dump file.To reload the dump into a new database called newdb:$ createdb -T template0 newdb$ pg_restore -d newdb db.dumpNotice we don't use -C, and instead connect directly to the database to be restored into. Also note that weclone the new database from template0 not template1, to ensure it is initially empty.To reorder database items, it is first necessary to dump the table of contents of the archive:$ pg_restore -l db.dump > db.listThe listing file consists of a header and one line for each item, e.g.:;; Archive created at Mon Sep 14 13:55:39 2009; dbname: DBDEMOS; TOC Entries: 81; Compression: 9; Dump Version: 1.10-0; Format: CUSTOM; Integer: 4 bytes; Offset: 8 bytes; Dumped from database version: 8.3.5; Dumped by pg_dump version: 8.3.8;;; Selected TOC Entries:;3; 2615 2200 SCHEMA - public pasha1861; 0 0 COMMENT - SCHEMA public pasha1862; 0 0 ACL - public pasha317; 1247 17715 TYPE public composite pasha319; 1247 25899 DOMAIN public domain0 pashaSemicolons start a comment, and the numbers at the start of lines refer to the internal archive ID assigned toeach item.Lines in the file can be commented out, deleted, and reordered. For example:10; 145433 TABLE map_resolutions postgres;2; 145344 TABLE species postgres;4; 145359 TABLE nt_header postgres6; 145402 TABLE species_records postgres;8; 145416 TABLE ss_old postgrescould be used as input to pg_restore and would only restore items 10 and 6, in that order:$ pg_restore -L db.list db.dump
pg_restore -U) ...