Backup and Restore

Updated · 10 min read
mediumPostgreSQL 18sqlbackuprestorepg-dumppoint-in-time-recoveryinterview

A database backup is a copy of a database's data, saved somewhere else, from which the database can be rebuilt after a mistake, a failure or an attack. A restore is the rebuilding. Backups protect against the things constraints and transactions can't: a dropped table, a bad deploy that corrupts thousands of rows, a failed disk, or ransomware. In this lesson, we will make a logical backup with pg_dump, look inside it, restore a dropped table from it, compare the kinds of backup (full, differential and point-in-time), and learn the rule that matters most: a backup is only real once you've restored it.

In One Minute

  • Logical backups (pg_dump, mysqldump) write SQL or an archive that recreates tables and rows.
  • Physical backups copy the database's files; with saved transaction logs they allow point-in-time recovery.
  • Full backups copy everything; differential and incremental copy only what changed.
  • Keep copies off the database server, and some offline or immutable.
  • Test restores regularly. An untested backup is a hope, not a plan.

Making a Logical Backup

pg_dump connects to a PostgreSQL database and writes out the SQL needed to recreate it. It works while the database is in use: everything it writes comes from one consistent snapshot, so a payment inserted halfway through the dump is either fully in it or fully out. Other sessions can keep reading and writing; only changes to the table definitions themselves (such as ALTER TABLE or DROP TABLE) wait until the dump finishes. From a terminal:

Shell
pg_dump -d feetracker -f feetracker.sql                         # whole database, as SQL
pg_dump -d feetracker -Fc -f feetracker.dump                    # custom archive (compressed)
pg_dump -d feetracker --table=payments --inserts -f payments.sql  # one table, as INSERTs
OptionMeans
-d feetrackerThe database to back up
-f fileWrite to this file
-FcCustom archive format: compressed, restored with pg_restore
--table=paymentsOnly this table
--insertsWrite rows as INSERT statements (by default, plain dumps use faster COPY blocks)

Here is the core of the real payments.sql that the last command produces for the Fee Tracker, with its comment lines and session settings left out:

SQL
CREATE TABLE public.payments (
    payment_id integer NOT NULL,
    student_id integer NOT NULL,
    course_id integer NOT NULL,
    amount_usd numeric(8,2) NOT NULL,
    due_on date NOT NULL,
    paid_on date NOT NULL,
    method character varying(10),
    CONSTRAINT payments_amount_usd_check CHECK ((amount_usd > (0)::numeric)),
    ...
);
 
ALTER TABLE public.payments ALTER COLUMN payment_id ADD GENERATED BY DEFAULT AS IDENTITY (...);
 
INSERT INTO public.payments VALUES (1, 101, 1, 450.00, '2025-09-01', '2025-08-28', 'card');
...
INSERT INTO public.payments VALUES (7, 103, 5, 225.00, '2025-12-15', '2025-12-19', 'check');
 
SELECT pg_catalog.setval('public.payments_payment_id_seq', 7, true);
 
ALTER TABLE ONLY public.payments
    ADD CONSTRAINT payments_pkey PRIMARY KEY (payment_id);
...

Explanation: A logical backup is ordinary SQL. It creates the table, inserts every row, resets the identity sequence so the next payment gets id 8, and only then adds the primary and foreign keys, which is faster than checking them row by row. The first lines (not shown) record the versions: Dumped from database version 18.7 and Dumped by pg_dump version 18.7.

pg_dump output in order: table definition, rows, sequence position, then keys and constraints

Restoring

A plain SQL dump is restored by running it, for example with psql -d feetracker -f payments.sql. Because the dump starts with CREATE TABLE, it expects the table not to exist yet: run it into a new database, or after the table was dropped. Custom archives use pg_restore, which can restore one table, run in parallel, and skip objects:

Shell
psql -d feetracker -f payments.sql                    # plain SQL dump
pg_restore -d feetracker --clean feetracker.dump      # custom archive, replacing what exists
pg_restore -d feetracker -t payments feetracker.dump  # just one table from the archive
createdb feetracker_check && pg_restore -d feetracker_check feetracker.dump  # restore test

The last line is the habit that matters: restore into a separate, new database and check it, without touching the real one.

The Fee Tracker dumped, restored into feetracker_check, and checked: every count and the payment total match

Kinds of Backup

KindWhat it copiesRestores toTools
Logical, fullSQL or archive of the whole databaseThe moment the dump startedpg_dump, mysqldump, BACKUP DATABASE
Physical, fullThe database filesThe moment the backup finishedpg_basebackup, cloud snapshots
DifferentialChanges since the last full backupThat backup's time (restored on top of the full)SQL Server WITH DIFFERENTIAL
IncrementalChanges since the last backup of any kindThat backup's time (the full plus every incremental since, in order)pg_basebackup --incremental (PostgreSQL 17+), many backup tools
Point-in-time (PITR)A physical backup plus every transaction log sinceAny moment in betweenPostgreSQL WAL archiving, MySQL binary logs, SQL Server log backups

Point-in-time recovery replays the transaction log up to a chosen moment, such as one second before someone ran DELETE FROM payments without a WHERE. Managed cloud databases usually offer it with a few clicks (Database Hosting).

Sunday full, daily differentials, and the log in between: PITR can stop just before the mistake

Backups in Other Databases

Shell
# MySQL: logical backup and restore
mysqldump --single-transaction feetracker > feetracker.sql   # consistent snapshot for InnoDB tables
mysql feetracker < feetracker.sql
SQL
-- SQL Server: full, differential and log backups
BACKUP DATABASE FeeTracker TO DISK = 'D:\backups\FeeTracker_full.bak';
BACKUP DATABASE FeeTracker TO DISK = 'D:\backups\FeeTracker_diff.bak' WITH DIFFERENTIAL;
BACKUP LOG FeeTracker TO DISK = 'D:\backups\FeeTracker_log.trn';
 
-- Restore: the full, then the differential, then the log up to just before the mistake
RESTORE DATABASE FeeTracker FROM DISK = 'D:\backups\FeeTracker_full.bak' WITH NORECOVERY;
RESTORE DATABASE FeeTracker FROM DISK = 'D:\backups\FeeTracker_diff.bak' WITH NORECOVERY;
RESTORE LOG FeeTracker FROM DISK = 'D:\backups\FeeTracker_log.trn'
    WITH STOPAT = '2026-01-07T14:14:00', RECOVERY;

WITH NORECOVERY keeps the database closed so more backups can be applied; WITH RECOVERY on the last step opens it. Point-in-time recovery in SQL Server needs the full recovery model, which keeps the log until it is backed up. Tabs showing each database's version are coming to this course.

A Backup Plan

QuestionA sensible answer for a small app
How much data can we lose? (RPO, recovery point objective)Minutes: point-in-time recovery
How long can we be down? (RTO, recovery time objective)An hour: a tested restore procedure
Where are copies kept?3-2-1 rule: 3 copies, on 2 kinds of storage, 1 off-site
How long are they kept?30 days of daily backups, 12 monthly
Who can delete backups?Almost nobody; use immutable or locked storage against ransomware

Common Mistakes

Never testing a restore. Many teams discover broken backups during an emergency.

Backups next to the database. One failure loses both.

Forgetting roles and settings. pg_dump dumps one database, without its roles or server settings; pg_dumpall --globals-only saves roles and tablespaces, and configuration files need their own copy.

Storing backups unencrypted. A backup contains every secret in the database; protect it like the database.

Interview Corner

What's the difference between logical and physical backups?

A logical backup (like pg_dump) writes SQL or an archive that recreates objects and rows; it's portable and can restore single tables. A physical backup copies the data files; it's faster for large databases and, with transaction logs, enables point-in-time recovery.

What is point-in-time recovery?

Restoring a physical backup and replaying the transaction log up to a chosen moment, such as just before an accidental delete.

What are RPO and RTO?

RPO (recovery point objective) is how much data you can afford to lose, measured in time. RTO (recovery time objective) is how long recovery may take.

Practice

Challenge (module checkpoint, part 1): Someone drops the payments table. Restore it by running the statements from the pg_dump backup above, then check that the row count and total match the original (7 payments, 2150.00) and that the next payment gets id 8.

Show solution
SQL▶ Try it
DROP TABLE payments;
 
CREATE TABLE public.payments (
    payment_id integer NOT NULL,
    student_id integer NOT NULL,
    course_id integer NOT NULL,
    amount_usd numeric(8,2) NOT NULL,
    due_on date NOT NULL,
    paid_on date NOT NULL,
    method character varying(10),
    CONSTRAINT payments_amount_usd_check CHECK ((amount_usd > (0)::numeric)),
    CONSTRAINT payments_method_check CHECK (((method)::text = ANY ((ARRAY['card'::character varying, 'check'::character varying, 'cash'::character varying])::text[])))
);
 
ALTER TABLE public.payments ALTER COLUMN payment_id ADD GENERATED BY DEFAULT AS IDENTITY (
    SEQUENCE NAME public.payments_payment_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1
);
 
INSERT INTO public.payments VALUES (1, 101, 1, 450.00, '2025-09-01', '2025-08-28', 'card');
INSERT INTO public.payments VALUES (2, 101, 2, 250.00, '2025-11-01', '2025-10-30', 'card');
INSERT INTO public.payments VALUES (3, 101, 2, 250.00, '2025-12-01', '2025-12-03', 'check');
INSERT INTO public.payments VALUES (4, 101, 3, 550.00, '2026-01-02', '2025-12-29', 'card');
INSERT INTO public.payments VALUES (5, 101, 4, 200.00, '2026-01-05', '2026-01-05', NULL);
INSERT INTO public.payments VALUES (6, 103, 5, 225.00, '2025-11-15', '2025-11-14', 'card');
INSERT INTO public.payments VALUES (7, 103, 5, 225.00, '2025-12-15', '2025-12-19', 'check');
 
SELECT pg_catalog.setval('public.payments_payment_id_seq', 7, true);
 
ALTER TABLE ONLY public.payments
    ADD CONSTRAINT payments_pkey PRIMARY KEY (payment_id);
ALTER TABLE ONLY public.payments
    ADD CONSTRAINT payments_course_id_fkey FOREIGN KEY (course_id) REFERENCES public.courses(course_id);
ALTER TABLE ONLY public.payments
    ADD CONSTRAINT payments_student_id_course_id_fkey FOREIGN KEY (student_id, course_id) REFERENCES public.enrollments(student_id, course_id);
ALTER TABLE ONLY public.payments
    ADD CONSTRAINT payments_student_id_fkey FOREIGN KEY (student_id) REFERENCES public.students(student_id);
 
SELECT count(*) AS payments, sum(amount_usd) AS total_usd FROM payments;
 
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 4, 100.00, '2026-01-05', '2026-01-05', 'card')
RETURNING payment_id;
Output
DROP TABLE
 
CREATE TABLE
 
ALTER TABLE
 
INSERT 0 1
 
INSERT 0 1
 
INSERT 0 1
 
INSERT 0 1
 
INSERT 0 1
 
INSERT 0 1
 
INSERT 0 1
 
 setval
--------
      7
(1 row)
 
ALTER TABLE
 
ALTER TABLE
 
ALTER TABLE
 
ALTER TABLE
 
 payments | total_usd
----------+-----------
        7 |   2150.00
(1 row)
 
 payment_id
------------
          8
(1 row)

The dump rebuilt the table, its rows, its constraints and its sequence position: 7 payments totaling 2150.00, and the next payment is 8. Part 2 of the checkpoint, adding a column safely, is in Schema Migrations.

Quick check: Backup and restore

3 questions
1What does pg_dump produce?
2Which backup type can restore to one second before an accidental DELETE?
3When is a backup known to work?

Key Takeaways

You want toRun
Back up a databasepg_dump -d feetracker -Fc -f feetracker.dump
Restore itpg_restore -d feetracker_check feetracker.dump
Back up one table as SQLpg_dump -d feetracker --table=payments -f payments.sql
Save rolespg_dumpall --globals-only -f roles.sql

Was this tutorial helpful?

Lesson 96 of 115