Skip to content

Instantly share code, notes, and snippets.

@basperheim
Created June 29, 2024 17:36
Show Gist options
  • Save basperheim/f540d5ae6288a4a6a03e0b3afd05ccf0 to your computer and use it in GitHub Desktop.
Save basperheim/f540d5ae6288a4a6a03e0b3afd05ccf0 to your computer and use it in GitHub Desktop.
Postgres 'pg_dump' overview to backup a database

Postgres 'pg_dump' backup overview

When using pg_dump to back up a PostgreSQL database, here are some important flags and options to consider:

  1. -d, --dbname=NAME: Specifies the name of the database to dump.

  2. -f, --file=FILENAME: Directs the output to the specified file or directory.

  3. -F, --format=c|t|p: Specifies the format of the output file (c for custom, t for tar, p for plain text SQL).

  4. -h, --host=HOSTNAME: Specifies the host name of the machine on which the server is running.

  5. -p, --port=PORT: Specifies the TCP port or local Unix socket file extension on which the server is listening for connections.

  6. -U, --username=NAME: Connect as the specified PostgreSQL user.

  7. -w, --no-password: Never issue a password prompt. Useful for scripting.

  8. -W, --password: Force password prompt (should be avoided in scripts for security reasons).

  9. -c, --clean: Clean (drop) database objects before recreating them.

  10. -j, --jobs=NUM: Use this many parallel jobs to dump large objects. This can speed up the dump process.

  11. --data-only: Dump only the data, not the schema.

  12. --schema-only: Dump only the schema, not the data.

  13. --inserts: Dump data as INSERT commands rather than COPY.

  14. --column-inserts: Dump data as INSERT commands with column names.

To back up everything including records, the default behavior of pg_dump is to include both schema (table definitions, functions, etc.) and data (records within tables). This ensures a complete backup of the database. If you want to include only data or only schema, you can use the --data-only or --schema-only options respectively.

For a basic backup of an entire database to a file named backup.sql, you might use a command like this:

pg_dump -U your_username -d your_database -f backup.sql

Adjust your_username and your_database with your actual PostgreSQL username and database name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment