PG_DUMP(1)
๐พ pg_dump โ the PostgreSQL 18.6 documentation era ๐
okay bestie, sit DOWN, because we are talking about pg_dump, which is genuinely one of the most iconic little programs in the whole PostgreSQL situation. it exports a PostgreSQL database as an SQL script or to other formats. that's the whole name. that's the whole job. and it does it SO well.
โจ NAME โจ
pg_dump โ export a PostgreSQL database as an SQL script or to other formats ๐ซถ
๐ธ SYNOPSIS ๐ธ
pg_dump [connection-option...] [option...] [dbname]
๐ DESCRIPTION ๐
okay so. pg_dump is a utility for exporting a PostgreSQL database. it makes consistent exports even if the database is being used concurrently โ like, people can be reading AND writing while you dump, and it still holds it together. no cap. and it does not block other users accessing the database (readers or writers, either one, it's not gatekeeping). ๐
but bestie, real talk: except in simple cases, pg_dump is generally not the right choice for taking regular backups of production databases. see Chapter 25 for further discussion. i know, i know, shocking. but that's what it says and i'm not gonna lie to you. ๐
pg_dump only dumps a single database. that's the whole vibe. it's a one-database girlie. if you want to export an entire cluster, or export global objects that are common to all databases in a cluster (such as roles and tablespaces), you need pg_dumpall(1) instead. different tool, different job, still iconic.
dumps can be output in script or archive file formats:
- script dumps are plain-text files containing the SQL commands required to reconstruct the database to the state it was in at the time it was saved. to restore from such a script, feed it to
psql(1). and here's the slay: script files can be used to reconstruct the database even on other machines and other architectures โ and with some modifications, even on other SQL database products. โจ - the alternative archive file formats must be used with
pg_restore(1)to rebuild the database. they letpg_restorebe selective about what is restored, or even to reorder the items prior to being restored. the archive file formats are designed to be portable across architectures. ๐
when used with one of the archive file formats and combined with pg_restore, pg_dump provides a flexible archival and transfer mechanism. you can export an entire database with pg_dump, then use pg_restore to examine the archive and/or select which parts of the database are to be restored. and the most flexible output file formats are the "custom" format (-Fc) and the "directory" format (-Fd). they allow for selection and reordering of all archived items, they support parallel restoration, and they are compressed by default. and the "directory" format is the only format that supports parallel dumps. periodt. ๐
while running pg_dump, one should examine the output for any warnings (printed on standard error), especially in light of the limitations listed below. read your warnings, bestie, they're trying to tell you something.
โ ๏ธ Warning โ ๏ธ restoring a dump causes the destination to execute arbitrary code of the source superusers' choice. and partial dumps and partial restores do not limit that. if the source superusers are not trusted, the dumped SQL statements must be inspected before restoring. non-plain-text dumps can be inspected by usingpg_restore's--fileoption. note that the client running the dump and restore need not trust the source or destination superusers. this one is genuinely serious, okay? i'm being cute but i'm not being cute about this. ๐
๐ OPTIONS ๐
the following command-line options control the content and format of the output. (the connection options are a whole other situation, we'll get there.)
dbnameโ specifies the name of the database to be dumped. if this is not specified, the environment variablePGDATABASEis used. and if that is not set, the user name specified for the connection is used. it's a whole fallback chain, she's resourceful. ๐-a,--data-onlyโ dump only the data, not the schema (data definitions) or statistics. table data, large objects, and sequence values are dumped. this option is similar to, but for historical reasons not identical to, specifying--section=data. (yes, they're cousins, not twins. don't @ me.)-b,--large-objects,--blobs(deprecated) โ include large objects in the dump. this is the default behavior except when--schema,--table,--schema-only,--statistics-only, or--no-datais specified. so the-bswitch is therefore only useful to add large objects to dumps where a specific schema or table has been requested. note that large objects are considered data and therefore will be included when--data-onlyis used, but not when--schema-onlyor--statistics-onlyis. ๐ง-B,--no-large-objects,--no-blobs(deprecated) โ exclude large objects in the dump. and when both-band-Bare given, the behavior is to output large objects, when data is being dumped โ see the-bdocumentation. so-bwins that fight, fyi.-c,--cleanโ output commands toDROPall the dumped database objects prior to outputting the commands for creating them. this option is useful when the restore is to overwrite an existing database. if any of the objects do not exist in the destination database, ignorable error messages will be reported during restore, unless--if-existsis also specified. (so if you hate the error spam, bring--if-existsalong.)-C,--createโ begin the output with a command to create the database itself and reconnect to the created database. (with a script of this form, it doesn't matter which database in the destination installation you connect to before running the script. love that for you.) if--cleanis also specified, the script drops and recreates the target database before reconnecting to it.
with --create, the output also includes the database's comment if any, and any configuration variable settings that are specific to this database โ that is, any ALTER DATABASE ... SET ... and ALTER ROLE ... IN DATABASE ... SET ... commands that mention this database. access privileges for the database itself are also dumped, unless --no-acl is specified.
this option is ignored when emitting an archive (non-text) output file. for the archive formats, you can specify the option when you call pg_restore.
-e pattern,--extension=patternโ dump only extensions matching pattern. when this option is not specified, all non-system extensions in the target database will be dumped. multiple extensions can be selected by writing multiple-eswitches. the pattern parameter is interpreted as a pattern according to the same rules used bypsql's\dcommands (see Patterns), so multiple extensions can also be selected by writing wildcard characters in the pattern. when using wildcards, be careful to quote the pattern if needed to prevent the shell from expanding the wildcards โ your shell is a menace and it WILL eat your asterisks. ๐ญ
any configuration relation registered by pg_extension_config_dump is included in the dump if its extension is specified by --extension.
Note ๐ when-eis specified,pg_dumpmakes no attempt to dump any other database objects that the selected extension(s) might depend upon. therefore, there is no guarantee that the results of a specific-extension dump can be successfully restored by themselves into a clean database. it's giving "you're on your own, bestie."
-E encoding,--encoding=encodingโ create the dump in the specified character set encoding. by default, the dump is created in the database encoding. (another way to get the same result is to set thePGCLIENTENCODINGenvironment variable to the desired dump encoding.) the supported encodings are described in Section 23.3.1. ๐-f file,--file=fileโ send output to the specified file. this parameter can be omitted for file based output formats, in which case the standard output is used. it must be given for the directory output format however, where it specifies the target directory instead of a file. in this case the directory is created bypg_dumpand must not exist before. (so don't go pre-making the folder. she wants to do it herself. main character energy.) ๐-F format,--format=formatโ selects the format of the output. format can be one of the following:p,plainโ output a plain-text SQL script file (the default).c,customโ output a custom-format archive suitable for input intopg_restore. together with the directory output format, this is the most flexible output format in that it allows manual selection and reordering of archived items during restore. this format is also compressed by default.d,directoryโ output a directory-format archive suitable for input intopg_restore. this will create a directory with one file for each table and large object being dumped, plus a so-called Table of Contents file describing the dumped objects in a machine-readable format thatpg_restorecan read. a directory format archive can be manipulated with standard Unix tools; for example, files in an uncompressed archive can be compressed with thegzip,lz4, orzstdtools. this format is compressed by default usinggzipand also supports parallel dumps. ๐ฅt,tarโ output a tar-format archive suitable for input intopg_restore. the tar format is compatible with the directory format: extracting a tar-format archive produces a valid directory-format archive. however, the tar format does not support compression. also, when using tar format the relative order of table data items cannot be changed during restore. ๐
-j njobs,--jobs=njobsโ run the dump in parallel by dumping njobs tables simultaneously. this option may reduce the time needed to perform the dump but it also increases the load on the database server. you can only use this option with the directory output format because this is the only output format where multiple processes can write their data at the same time. (it's the only format that can share, okay?)
pg_dump will open njobs + 1 connections to the database, so make sure your max_connections setting is high enough to accommodate all connections. do the math before you commit, bestie. ๐งฎ
requesting exclusive locks on database objects while running a parallel dump could cause the dump to fail. the reason is that the pg_dump leader process requests shared locks (ACCESS SHARE) on the objects that the worker processes are going to dump later in order to make sure that nobody deletes them and makes them go away while the dump is running. if another client then requests an exclusive lock on a table, that lock will not be granted but will be queued waiting for the shared lock of the leader process to be released. consequently any other access to the table will not be granted either and will queue after the exclusive lock request. this includes the worker process trying to dump the table. without any precautions this would be a classic deadlock situation. ๐ to detect this conflict, the pg_dump worker process requests another shared lock using the NOWAIT option. if the worker process is not granted this shared lock, somebody else must have requested an exclusive lock in the meantime and there is no way to continue with the dump, so pg_dump has no choice but to abort the dump.
to be continued, bestieโฆ ๐ธ
So, about pg_dump -j real quick, because this is important and also lowkey iconic: parallel dump only works if the database server supports synchronized snapshots, a feature that landed in PostgreSQL 9.2 for primary servers and 10 for standbys. With it, database clients can make sure they see the exact same data set even though they're using different connections. pg_dump -j uses multiple database connections โ it connects to the database once with the leader process, and once again for each worker job. Without the synchronized snapshot feature, those different worker jobs wouldn't be guaranteed to see the same data on each connection, which could lead to an inconsistent backup. ๐ Not the vibe.
-n pattern,--schema=patternโ dump only schemas matching pattern; this selects both the schema itself and all the objects chillin' inside it. If you don't specify this option, all non-system schemas in the target database get dumped. Wanna pick multiple schemas? Just write multiple-nswitches, bestie. The pattern parameter is interpreted as a pattern using the exact same rules aspsql's\dcommands (see Patterns), so you can also select multiple schemas by throwing wildcard characters into the pattern. When you use wildcards, be careful to quote the pattern if needed so the shell doesn't expand the wildcards first โ see Examples below. ๐
Note โจ When-nis specified,pg_dumpmakes no attempt to dump any other database objects that the selected schema(s) might depend upon. So there's genuinely no guarantee that the results of a specific-schema dump can be successfully restored by themselves into a clean database. It's giving "self-contained but maybe not", fr.
Note ๐ Non-schema objects such as large objects are not dumped when-nis specified. You can add large objects back to the dump with the--large-objectsswitch.
-N pattern,--exclude-schema=patternโ do not dump any schemas matching pattern. The pattern is interpreted using the same rules as for-n.-Ncan be given more than once, so you can exclude schemas matching any of several patterns. When both-nand-Nare given, the behavior is to dump just the schemas that match at least one-nswitch but no-Nswitches. If-Nshows up without-n, then schemas matching-Nare excluded from what would otherwise be a normal dump. ๐-O,--no-ownerโ don't output commands to set ownership of objects to match the original database. By default,pg_dumpissuesALTER OWNERorSET SESSION AUTHORIZATIONstatements to set ownership of created database objects. Those statements will fail when the script is run unless it's started by a superuser (or the same user that owns all the objects in the script). To make a script that can be restored by any user โ but will give that user ownership of all the objects โ specify-O. This option is ignored when emitting an archive (non-text) output file. For the archive formats, you can specify the option when you callpg_restore. ๐-R,--no-reconnectโ this option is obsolete but still accepted for backwards compatibility. She's retired but still shows up to the function, iykyk. ๐-s,--schema-onlyโ dump only the object definitions (schema), not data or statistics. This option cannot be used with--data-onlyor--statistics-only. It's similar to โ but for historical reasons not identical to โ specifying--section=pre-data --section=post-data. (Do not confuse this with the--schemaoption, which uses the word โschemaโ in a whole different meaning. Same word, different girl. ๐ญ) To exclude table data for only a subset of tables in the database, see--exclude-table-data.-S username,--superuser=usernameโ specify the superuser user name to use when disabling triggers. This is relevant only if--disable-triggersis used. (Usually, it's better to leave this out, and instead start the resulting script as superuser. Just saying. ๐)-t pattern,--table=patternโ dump only tables with names matching pattern. Multiple tables can be selected by writing multiple-tswitches. The pattern parameter is interpreted as a pattern using the same rules aspsql's\dcommands (see Patterns), so multiple tables can also be selected by writing wildcard characters in the pattern. When using wildcards, be careful to quote the pattern if needed so the shell doesn't expand the wildcards โ see Examples below. ๐ธ
As well as tables, this option can be used to dump the definition of matching views, materialized views, foreign tables, and sequences. It will not dump the contents of views or materialized views, and the contents of foreign tables will only be dumped if the corresponding foreign server is specified with --include-foreign-data.
The -n and -N switches have no effect when -t is used, because tables selected by -t will be dumped regardless of those switches, and non-table objects will not be dumped. Periodt.
Note ๐ฆ When-tis specified,pg_dumpmakes no attempt to dump any other database objects that the selected table(s) might depend upon. Therefore, there is no guarantee that the results of a specific-table dump can be successfully restored by themselves into a clean database. Same energy as the-nwarning, different day.
-T pattern,--exclude-table=patternโ do not dump any tables matching pattern. The pattern is interpreted using the same rules as for-t.-Tcan be given more than once to exclude tables matching any of several patterns. When both-tand-Tare given, the behavior is to dump just the tables that match at least one-tswitch but no-Tswitches. If-Tappears without-t, then tables matching-Tare excluded from what is otherwise a normal dump. โจ-v,--verboseโ specifies verbose mode. This makespg_dumpoutput detailed object comments and start/stop times to the dump file, plus progress messages to standard error. Repeating the option causes additional debug-level messages to appear on standard error. Spam me with the receipts, honestly. ๐ฅ-V,--versionโ print thepg_dumpversion and exit. Short and sweet. ๐-x,--no-privileges,--no-aclโ prevent dumping of access privileges (grant/revoke commands). No permissions drama in your dump file. ๐ซ-Z level,-Z method[:detail],--compress=level,--compress=method[:detail]โ specify the compression method and/or the compression level to use. The compression method can be set togzip,lz4,zstd, ornonefor no compression. A compression detail string can optionally be specified. If the detail string is an integer, it specifies the compression level. Otherwise, it should be a comma-separated list of items, each of the formkeywordorkeyword=value. Currently, the supported keywords arelevelandlong.
If no compression level is specified, the default compression level will be used. If only a level is specified without mentioning an algorithm, gzip compression will be used if the level is greater than 0, and no compression will be used if the level is 0.
For the custom and directory archive formats, this specifies compression of individual table-data segments, and the default is to compress using gzip at a moderate level. For plain text output, setting a nonzero compression level causes the entire output file to be compressed, as though it had been fed through gzip, lz4, or zstd โ but the default is not to compress. With zstd compression, long mode may improve the compression ratio, at the cost of increased memory use. And the tar archive format currently does not support compression at all. Not a single bit. ๐ญ
--binary-upgradeโ this option is for use by in-place upgrade utilities. Its use for other purposes is not recommended or supported. The behavior of the option may change in future releases without notice. It's giving "for internal use only, don't touch". ๐--column-inserts,--attribute-insertsโ dump data asINSERTcommands with explicit column names (INSERT INTO table (column, ...) VALUES ...). This will make restoration very slow; it's mainly useful for making dumps that can be loaded into non-PostgreSQL databases. The upside? Any error during restoring will cause only the rows that are part of the problematicINSERTto be lost, rather than the entire table contents. Silver lining moment. ๐--disable-dollar-quotingโ this option disables the use of dollar quoting for function bodies, and forces them to be quoted using SQL standard string syntax. ๐--disable-triggersโ this option is relevant only when creating a dump that includes data but does not include schema. It instructspg_dumpto include commands to temporarily disable triggers on the target tables while the data is restored. Use this if you have referential integrity checks or other triggers on the tables that you do not want to invoke during data restore. Presently, the commands emitted for--disable-triggersmust be done as superuser. So you should also specify a superuser name with-S, or preferably be careful to start the resulting script as a superuser. This option is ignored when emitting an archive (non-text) output file. For the archive formats, you can specify the option when you callpg_restore.--enable-row-securityโ this option is relevant only when dumping the contents of a table which has row security. By default,pg_dumpwill setrow_securitytooff, to ensure that all data is dumped from the table. If the user does not have sufficient privileges to bypass row security, then an error is thrown. This parameter instructspg_dumpto setrow_securitytooninstead, allowing the user to dump the parts of the contents of the table that they have access to. Note that if you use this option currently, you probably also want the dump to be inINSERTformat, as theCOPY FROMduring restore does not support row security. ๐--exclude-extension=patternโ do not dump any extensions matching pattern. The pattern is interpreted using the same rules as for-e.--exclude-extensioncan be given more than once to exclude extensions matching any of several patterns. When both-eand--exclude-extensionare given, the behavior is to dump just the extensions that match at least one-eswitch but no--exclude-extensionswitches. If--exclude-extensionappears without-e, then extensions matching--exclude-extensionare excluded from what is otherwise a normal dump. ๐
--exclude-table-and-children=patternโ bestie, this is literally the same as-T/--exclude-table, except it also excludes any partitions or inheritance child tables of the table(s) matching pattern. ๐ซถ--exclude-table-data=patternโ no data for you for any tables matching pattern. The pattern gets interpreted by the exact same rules as-t. You can drop--exclude-table-datamore than once and it'll exclude tables matching any of several patterns. Iconic use case: you need a particular table's definition even though you do not need the data inside it. ๐
Wanna exclude data for every single table in the database? Go look at --schema-only or --statistics-only.
--exclude-table-data-and-children=patternโ same energy as--exclude-table-data, except it also excludes the data of any partitions or inheritance child tables of the table(s) matching pattern. ๐--extra-float-digits=ndigitsโ use the value you give here asextra_float_digitswhen dumping floating-point data, instead of the maximum available precision. Heads up bestie: routine dumps made for backup purposes should not use this option. ๐--filter=filenameโ give it a filename and it'll read patterns from there for objects to include or exclude from the dump. Those patterns get interpreted by the same rules as their corresponding options:-t/--table,--table-and-children,-T/--exclude-table, and--exclude-table-and-childrenfor tables;-n/--schemaand-N/--exclude-schemafor schemas;--include-foreign-datafor data on foreign servers;--exclude-table-dataand--exclude-table-data-and-childrenfor table data; and-e/--extensionand--exclude-extensionfor extensions. Wanna read from STDIN? Use-as the filename. ๐ You can run--filterright alongside all those include/exclude options above, and you can also specify it more than once for multiple filter files. Periodt.
The file lists one object pattern per row, formatted like this:
{ include | exclude } { extension | foreign_data | table | table_and_children | table_data | table_data_and_children | schema } PATTERN
The first keyword says whether the objects matched by the pattern get included or excluded. The second keyword says what type of object the pattern is filtering: โจ
- extension: extensions. Works like the
-e/--extensionor--exclude-extensionoption. - foreign_data: data on foreign servers. Works like the
--include-foreign-dataoption. This keyword can only be used with theincludekeyword. - table: tables. Works like the
-t/--tableor-T/--exclude-tableoption. - table_and_children: tables including any partitions or inheritance child tables. Works like the
--table-and-childrenor--exclude-table-and-childrenoption. - table_data: table data of any tables matching pattern. Works like the
--exclude-table-dataoption. This keyword can only be used with theexcludekeyword. - table_data_and_children: table data of any tables matching pattern as well as any partitions or inheritance children of the table(s). Works like the
--exclude-table-data-and-childrenoption. This keyword can only be used with theexcludekeyword. - schema: schemas. Works like the
-n/--schemaor-N/--exclude-schemaoption.
Lines starting with # are treated as comments and ignored โ and yes, you can also stick a comment after an object pattern row. Blank lines get ignored too. For how to do quoting inside patterns, check out Patterns. ๐
Example files are listed below in the Examples section.
--if-existsโ useDROP ... IF EXISTScommands to drop objects while in--cleanmode. This shuts up the โdoes not existโ errors that might otherwise get reported. Not valid unless--cleanis also specified. ๐จ--include-foreign-data=foreignserverโ dumps the data for any foreign table whose foreign server matches the foreignserver pattern. Wanna grab multiple foreign servers? Just write multiple--include-foreign-dataswitches. Also, foreignserver is interpreted as a pattern by the same rulespsql's\dcommands use (see Patterns), so you can also select multiple foreign servers by throwing wildcard characters in the pattern. When you use wildcards, quote the pattern if you need to so the shell doesn't expand them first โ see Examples below. The one and only exception: an empty pattern is disallowed. ๐ซ
Note โ using wildcards in --include-foreign-data may result in access to unexpected foreign servers. And to use this option securely, make sure the named server has a trusted owner. ๐
Note โ when--include-foreign-datais specified,pg_dumpdoes not check that the foreign table is writable. So there's no guarantee that the results of a foreign table dump can be successfully restored. ๐ญ
--insertsโ dump data asINSERTcommands (instead ofCOPY). This makes restoration very slow; it's mainly useful for making dumps that can be loaded into non-PostgreSQL databases. The upside: any error during restoring only loses the rows that are part of the problematicINSERT, rather than the entire table contents. But bestie, note the restore might fail altogether if you've rearranged column order. The--column-insertsoption is safe against column order changes, though it's even slower. ๐--load-via-partition-rootโ when dumping data for a table partition, make theCOPYorINSERTstatements target the root of the partitioning hierarchy that contains it, instead of the partition itself. That way the appropriate partition gets re-determined for each row when the data is loaded. Super useful when you're restoring data on a server where rows don't always land in the same partitions they did on the original server. When does that even happen? Say the partitioning column is of typetextand the two systems have different definitions of the collation used to sort the partitioning column. ๐ฆ--lock-wait-timeout=timeoutโ do not wait forever to acquire shared table locks at the beginning of the dump. Instead it fails if it can't lock a table within the specified timeout. The timeout can be given in any of the formats accepted bySET statement_timeout. (Allowed formats vary depending on the server version you're dumping from, but an integer number of milliseconds is accepted by all versions.) โณ--no-commentsโ don't dumpCOMMENTcommands. ๐--no-dataโ don't dump data. ๐--no-policiesโ don't dump row security policies. ๐--no-publicationsโ don't dump publications. ๐--no-schemaโ don't dump schema (data definitions). ๐--no-security-labelsโ don't dump security labels. ๐--no-statisticsโ don't dump statistics. This is the default. โจ--no-subscriptionsโ don't dump subscriptions. ๐--no-syncโ by default,pg_dumpwaits for all files to be written safely to disk. This option makespg_dumpreturn without waiting, which is faster, but means a subsequent operating system crash can leave the dump corrupt. Generally this option is useful for testing but should not be used when dumping data from a production installation. ๐ฌ--no-table-access-methodโ don't output commands to select table access methods. With this option, all objects get created with whichever table access method is the default during restore. ๐
This option is ignored when emitting an archive (non-text) output file. For the archive formats, you can specify the option when you call pg_restore.
--no-tablespacesโ don't output commands to select tablespaces. With this option, all objects get created in whichever tablespace is the default during restore. ๐
This option is ignored when emitting an archive (non-text) output file. For the archive formats, you can specify the option when you call pg_restore.
--no-toast-compressionโ don't output commands to set TOAST compression methods. With this option, all columns get restored with the default compression setting. ๐ซถ--no-unlogged-table-dataโ don't dump the contents of unlogged tables and sequences. This option has no effect on whether the table and sequence definitions (schema) get dumped; it only suppresses dumping the table and sequence data. FYI: data in unlogged tables and sequences is always excluded when dumping from a standby server. ๐--on-conflict-do-nothingโ addsON CONFLICT DO NOTHINGtoINSERTcommands. Not valid unless--inserts,--column-insertsor--rows-per-insertis also specified. ๐จ--quote-all-identifiersโ force quoting of all identifiers. This one is recommended when you're dumping a database from a server whose PostgreSQL major version differs frompg_dump's, or when the output is meant to be loaded into a server of a different major version. By default,pg_dumponly quotes identifiers that are reserved words in its own major version โ which sometimes causes compatibility issues when you're dealing with servers of other versions that may have slightly different sets of reserved words. Using--quote-all-identifiersprevents those issues, at the price of a harder-to-read dump script. ๐--restrict-key=restrict_keyโ use the string you provide as thepsql\restrictkey in the dump output. This can only be specified for plain-text dumps, i.e., when--formatis set toplainor the--formatoption is omitted. If no restrict key is specified,pg_dumpwill generate a random one as needed. Keys may contain only alphanumeric characters. ๐
This option is primarily intended for testing purposes and other scenarios that require repeatable output (e.g., comparing dump files). It is not recommended for general use, because a malicious server with advance knowledge of the key may be able to inject arbitrary code that will be executed on the machine that runs psql with the dump output. ๐ฑ
--rows-per-insert=nrowsโ okay so this one dumps the data asINSERTcommands instead ofCOPY, and it lets you cap how many rows go in eachINSERT. The value you pass must be a number bigger than zero, no zero, no negative, don't try it ๐ . The cute part? If restoring hits an error, only the rows chillin' inside that one problematicINSERTget lost โ not the whole entire table's contents. glow-up fr fr โจ--section=sectionnameโ only dump the section you name. The section name can bepre-data,data, orpost-data. You can pass this option more than once to grab multiple sections at once, slay. Default vibe is dump all the sections.- The data section holds the actual table data, large-object contents, sequence values, and statistics for tables, materialized views, and foreign tables.
- Post-data items include definitions of indexes, triggers, rules, statistics for indexes, and constraints other than validated check and not-null constraints.
- Pre-data items include all other data definition items.
--sequence-dataโ include sequence data in the dump. This is the default behavior โจ except when--no-data,--schema-only, or--statistics-onlyis specified.--serializable-deferrableโ use a serializable transaction for the dump so the snapshot used is consistent with later database states ๐ฆ. But it does this by waiting for a point in the transaction stream where no anomalies can be present, so there's no risk of the dump failing or making other transactions roll back with aserialization_failure. See Chapter 13 for more on transaction isolation and concurrency control.
Heads up bestie: this option is not beneficial for a dump that's only meant for disaster recovery.
It could be useful for a dump used to load a copy of the database for reporting or other read-only load sharing while the original database keeps getting updated. Without it, the dump may reflect a state that isn't consistent with any serial execution of the transactions that eventually commit. Example: if batch processing techniques are used, a batch may show as closed in the dump without all of the items that are in the batch appearing. ๐ญ
This option makes no difference if there are no read-write transactions active when pg_dump is started. If read-write transactions are active, the start of the dump may be delayed for an indeterminate length of time. Once running, performance with or without the switch is the same. periodt.
--snapshot=snapshotnameโ use the specified synchronized snapshot when making a dump of the database (see Table 9.100 for more details) ๐.
This is the move when you need to synchronize the dump with a logical replication slot (see Chapter 47) or with a concurrent session.
And if it's a parallel dump? The snapshot name defined by this option is used instead of taking a new snapshot. iconic.
--statisticsโ dump optimizer statistics. ๐--statistics-onlyโ dump only the statistics, not the schema (data definitions) or data. Optimizer statistics for tables, materialized views, foreign tables, and indexes are dumped. โจ--strict-namesโ require that each extension (-e/--extension), schema (-n/--schema) and table (-t/--table) pattern match at least one extension/schema/table in the database being dumped. This also applies to filters used with--filter. Note that if none of the extension/schema/table patterns find matches,pg_dumpwill generate an error even without--strict-names. ๐
This option has no effect on --exclude-extension, -N/--exclude-schema, -T/--exclude-table, or --exclude-table-data. An exclude pattern failing to match any objects is not considered an error. ๐
--sync-method=methodโ when set tofsync, which is the default,pg_dump --format=directorywill recursively open and synchronize all files in the archive directory.
On Linux, syncfs may be used instead to ask the operating system to synchronize the whole file system that contains the archive directory. See recovery_init_sync_method for info about the caveats to be aware of when using syncfs. ๐ซถ
This option has no effect when --no-sync is used or --format is not set to directory.
--table-and-children=patternโ this is the same as the-t/--tableoption, except it also includes any partitions or inheritance child tables of the table(s) matching the pattern. family reunion energy ๐--use-set-session-authorizationโ output SQL-standardSET SESSION AUTHORIZATIONcommands instead ofALTER OWNERcommands to determine object ownership. This makes the dump more standards-compatible, but depending on the history of the objects in the dump, might not restore properly ๐ญ. Also, a dump usingSET SESSION AUTHORIZATIONwill certainly require superuser privileges to restore correctly, whereasALTER OWNERrequires lesser privileges.-?,--helpโ show help aboutpg_dumpcommand line arguments, and exit. ๐
The following command-line options control the database connection parameters.
-ddbname,--dbname=dbnameโ specifies the name of the database to connect to. This is equivalent to specifying dbname as the first non-option argument on the command line. The dbname can be a connection string. If so, connection string parameters will override any conflicting command line options. sneaky but valid ๐-hhost,--host=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 thePGHOSTenvironment variable, if set, else a Unix domain socket connection is attempted. ๐ธ-pport,--port=portโ specifies the TCP port or local Unix domain socket file extension on which the server is listening for connections. Defaults to thePGPORTenvironment variable, if set, or a compiled-in default. โจ-Uusername,--username=usernameโ user name to connect as.-w,--no-passwordโ never issue a password prompt. If the server requires password authentication and a password is not available by other means such as a.pgpassfile, the connection attempt will fail ๐. This option can be useful in batch jobs and scripts where no user is present to enter a password.-W,--passwordโ forcepg_dumpto prompt for a password before connecting to a database.
This option is never essential, since pg_dump will automatically prompt for a password if the server demands password authentication. However, pg_dump will waste a connection attempt finding out that the server wants a password. In some cases it is worth typing -W to avoid the extra connection attempt. lowkey efficient ๐
--role=rolenameโ specifies a role name to be used to create the dump. This option causespg_dumpto issue aSET ROLErolename command after connecting to the database. It's useful when the authenticated user (specified by-U) lacks privileges needed bypg_dump, but can switch to a role with the required rights. Some installations have a policy against logging in directly as a superuser, and use of this option allows dumps to be made without violating the policy. โจ
๐ ENVIRONMENT ๐
PGDATABASEPGHOSTPGOPTIONSPGPORTPGUSER
These are default connection parameters. ๐
PG_COLORโ specifies whether to use color in diagnostic messages. Possible values arealways,autoandnever. ๐ธ
This utility, like most other PostgreSQL utilities, also uses the environment variables supported by libpq (see Section 32.15).
๐ DIAGNOSTICS ๐
pg_dump internally executes SELECT statements. So if you're having problems running pg_dump, make sure you're able to select information from the database using, for example, psql(1). Also, any default connection settings and environment variables used by the libpq front-end library will apply. ๐ฆ
The database activity of pg_dump is normally collected by the cumulative statistics system. If that's not the vibe, you can set parameter track_counts to false via PGOPTIONS or the ALTER USER command. โจ
๐ NOTES ๐
ok so real talk, bestie โ this section is the "read before you wreck your whole weekend" part, and honestly it's giving โจwisdomโจ. buckle up ๐
If your database cluster has any local additions to the template1 database, be careful when restoring the output of pg_dump into a truly empty database โ otherwise you're lowkey likely to get errors because the added objects get defined twice. ๐ To make an empty database with no local additions, copy from template0 and not template1, like this:
CREATE DATABASE foo WITH TEMPLATE template0;
When you pick a dump without schema and also use the --disable-triggers option, pg_dump emits commands to disable triggers on user tables before it inserts the data, and then emits commands to re-enable them after the data has been inserted. ๐ซถ So far so cute โ but if the restore gets stopped in the middle, the system catalogs might be left in the wrong state. ๐ not the vibe.
When --statistics is specified, pg_dump will include most optimizer statistics in the resulting dump file. Keyword: most. It does not include all statistics โ like the ones created explicitly with CREATE STATISTICS (CREATE_STATISTICS(7)), custom statistics added by an extension, or statistics collected by the cumulative statistics system. So it may still be useful to run ANALYZE after restoring from a dump file to make sure performance is optimal; see Section 24.1.3 and Section 24.1.6 for more info. ๐ธ
Because pg_dump is used to transfer data to newer versions of PostgreSQL, the output of pg_dump can be expected to load into PostgreSQL server versions newer than pg_dump's version. pg_dump can also dump from PostgreSQL servers older than its own version (currently, servers back to version 9.2 are supported). ๐
However โ and this is the part where we pay attention โ pg_dump cannot dump from PostgreSQL servers newer than its own major version. It will refuse to even try, rather than risk making an invalid dump. no cap, it just says no. ๐ซ
Also, it is not guaranteed that pg_dump's output can be loaded into a server of an older major version โ not even if the dump was taken from a server of that version. Loading a dump file into an older server may require manual editing of the dump file to remove syntax the older server doesn't understand. Use of the --quote-all-identifiers option is recommended in cross-version cases, because it can prevent problems that arise from varying reserved-word lists in different PostgreSQL versions. ๐
When dumping logical replication subscriptions, pg_dump will generate CREATE SUBSCRIPTION commands that use the connect = false option, so that restoring the subscription does not make remote connections for creating a replication slot or for the initial table copy. That way, the dump can be restored without requiring network access to the remote servers. โจ It is then up to you (the user, the main character) to reactivate the subscriptions in a suitable way. If the involved hosts have changed, the connection information might have to be changed. It might also be appropriate to truncate the target tables before initiating a new full table copy. If users intend to copy initial data during refresh they must create the slot with two_phase = false. After the initial sync, the two_phase option will be automatically enabled by the subscriber if the subscription had been originally created with the two_phase = true option. ๐ฆ
And finally, the general recommendation: use the -X (--no-psqlrc) option when restoring a database from a plain-text pg_dump script. It keeps the restore process clean and prevents potential conflicts with non-default psql configurations. chef's kiss, honestly. ๐
๐ EXAMPLES ๐
okay this is the part everyone actually reads, and honestly? iconic. here's every single one. ๐
To dump a database called mydb into an SQL-script file:
$ pg_dump mydb > db.sql
To reload such a script into a (freshly created) database named newdb:
$ psql -X -d newdb -f db.sql
To dump a database into a custom-format archive file:
$ pg_dump -Fc mydb > db.dump
To dump a database into a directory-format archive:
$ pg_dump -Fd mydb -f dumpdir
To dump a database into a directory-format archive in parallel with 5 worker jobs:
$ pg_dump -Fd mydb -j 5 -f dumpdir
To reload an archive file into a (freshly created) database named newdb:
$ pg_restore -d newdb db.dump
To reload an archive file into the same database it was dumped from, discarding the current contents of that database:
$ pg_restore -d postgres --clean --create db.dump
To dump a single table named mytab:
$ pg_dump -t mytab mydb > db.sql
To dump all tables whose names start with emp in the detroit schema, except for the table named employee_log:
$ pg_dump -t 'detroit.emp*' -T detroit.employee_log mydb > db.sql
To dump all schemas whose names start with east or west and end in gsm, excluding any schemas whose names contain the word test:
$ pg_dump -n 'east*gsm' -n 'west*gsm' -N '*test*' mydb > db.sql
The same, using regular expression notation to consolidate the switches:
$ pg_dump -n '(east|west)*gsm' -N '*test*' mydb > db.sql
To dump all database objects except for tables whose names begin with ts_:
$ pg_dump -T 'ts_*' mydb > db.sql
To specify an upper-case or mixed-case name in -t and related switches, you need to double-quote the name; else it will be folded to lower case (see Patterns). But double quotes are special to the shell, so in turn they must be quoted. ๐ Thus, to dump a single table with a mixed-case name, you need something like
$ pg_dump -t "\"MixedCaseName\"" mydb > mytab.sql
To dump all tables whose names start with mytable, except for table mytable2, specify a filter file filter.txt like:
include table mytable*
exclude table mytable2
$ pg_dump --filter=filter.txt mydb > db.sql
๐ฆ SEE ALSO ๐ฆ
and that's the whole page bestie!! ๐ซถ go forth and dump responsibly, you absolute database legend. this was PostgreSQL 18.6, dated 2026 โ mwah ๐ โจ
๐ฆ where this page comes from
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- opensuse-leap 16.0: postgresql18 18.6-160000.1.1 ยท PostgreSQL
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms