AI Hints
Home›PostgreSQL Tutorial›Backups and Replication
PostgreSQL · Lesson 94 of 120

Backups with pg_dump

Save a copy.

⏱ 2 min read▶ Video at 1:24:43🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Hardware fails, and people make mistakes. Pg dump writes a whole database to a file, while it keeps running. It's the simplest backup.

  • Failures happen
  • pg_dump
  • While running

Dump the database

Pg dump with format c writes a compressed custom format file. We check the file size. A plain SQL dump is human readable, here just the books table schema. Run it. A small backup file, and readable SQL.

backup.shbash
docker exec pg pg_dump -U postgres -d riverside -Fc -f /tmp/riverside.dump
docker exec pg ls -lh /tmp/riverside.dump | awk '{print $5, $9}'

docker exec pg pg_dump -U postgres -d riverside -t books --schema-only \
  | grep -A6 'CREATE TABLE' 
Output
47K /tmp/riverside.dump
CREATE TABLE public.books (
    book_id integer NOT NULL,
    title text NOT NULL,
    author text NOT NULL,
    genre text NOT NULL,
    price numeric(6,2) NOT NULL,
    stock integer NOT NULL,

pg_dump formats

Custom format is compressed, and lets you restore single tables. Plain format is a SQL script. Directory format can dump in parallel. And pg dump all includes roles and every database.

keyvalue
-Fccustom, flexible
plainSQL script
-Fd -j 4parallel
pg_dumpallroles + all DBs

Summary

Pg dump saves a database to a file while it keeps running. Next, restoring it.

Key takeaways
  • pg_dump
  • -Fc
  • Schema only
Next up: Restore and Point-in-Time Recovery — get it back