article thumbnail

Database Backup and Restore

A backup you've never restored is just a hope

17 min read
#databases, #postgresql, #mysql, #mssql, #sqlite, #backup, #friday3

Every database administrator eventually learns this lesson, and the lucky ones learn it from someone else's disaster: nobody cares about your backups until the day they need one. A dropped table, a bad UPDATE with no WHERE, a dead disk, a ransomware note -- and suddenly the only question that matters is "When was the last good copy, and can we actually restore it?"

This article is a practical tour of backing up and restoring the databases most of us run -- PostgreSQL, MySQL/MariaDB, Microsoft SQL Server, and SQLite -- plus the habits that turn backups from a hope into a plan. (Commands were checked against the current docs as of this writing: PostgreSQL 18, MySQL 9.7 LTS and 8.4 LTS, and SQL Server 2025. Older versions behave the same unless noted.)


Two Kinds of Backup

Before any command, understand the one distinction that organizes everything:

Logical backup Physical backup
What it is SQL statements (or a portable dump) that recreate the data A copy of the actual database files on disk
Tools pg_dump, mysqldump, MySQL Shell dump, SQLite .dump, SQL Server bacpac export pg_basebackup, Percona XtraBackup, mariadb-backup, SQL Server BACKUP DATABASE, file snapshots
Size Smaller, human-readable Larger, byte-for-byte
Restore speed Slower (rebuilds indexes, replays inserts) Much faster on big databases
Portable across versions? Yes -- usually restores into newer versions No -- same major version and platform
Point-in-time recovery No (just a snapshot in time) Yes, when combined with transaction logs
Best for Small-to-medium databases, migrations, single tables Large databases, tight recovery time goals

Most teams use both: logical dumps for flexibility and portability, physical backups plus logs for speed and point-in-time recovery.


The 3-2-1 Rule

A backup sitting on the same disk as the database is not a backup -- it dies with the disk. The classic rule:

Modern tweak: make at least one copy immutable or offline so ransomware or a fat-fingered rm -rf can't reach it.


PostgreSQL: pg_dump

pg_dump makes a consistent snapshot of one database, even while it's in use, without blocking readers or writers. It supports several formats:

Flag Format Notes
-Fp Plain SQL Default. Readable, restore with psql
-Fc Custom Compressed, flexible restore with pg_restore
-Fd Directory Allows parallel dump (-j) and restore
-Ft Tar Rarely worth choosing over custom or directory
# Plain SQL, compressed on the fly
pg_dump myapp | gzip > myapp_2026-11-20.sql.gz

# Custom format (my usual choice)
pg_dump -Fc -f myapp_2026-11-20.dump myapp

# Directory format, 4 parallel jobs -- fastest for big databases
pg_dump -Fd -j 4 -f myapp_dump_dir myapp

Roles and tablespaces are not in pg_dump. They belong to the whole cluster, so capture them separately:

pg_dumpall --globals-only > globals.sql

Restoring a pg_dump

# Plain SQL -- stop at the first error and wrap it all in one transaction
psql -v ON_ERROR_STOP=1 -1 -d myapp_restored -f myapp_2026-11-20.sql

# Custom or directory format -- pg_restore, with parallel jobs
createdb myapp_restored
pg_restore -d myapp_restored -j 4 myapp_2026-11-20.dump

# Restore just one table
pg_restore -d myapp_restored -t orders myapp_2026-11-20.dump

# See what's inside a dump without restoring it
pg_restore -l myapp_2026-11-20.dump

Two flags save you grief: ON_ERROR_STOP=1 (so a failure doesn't scroll past unnoticed) and -1 (single transaction -- it either fully restores or leaves nothing half-done). If you restore into an existing database, pg_restore --clean --if-exists drops objects first.

New to the command line client? See A Guide to PSQL.


PostgreSQL: Physical Backups and Point-in-Time Recovery

Dumps are a snapshot of one moment. What if the disaster happens at 2:47 PM, and your last dump was at midnight? That's 14 hours of lost work. Point-in-time recovery (PITR) fixes this by combining a base backup with a continuous stream of the write-ahead log (WAL).

1. Take a base backup:

pg_basebackup -D /backups/base_2026-11-20 -Ft -z -P

2. Archive WAL continuously (in postgresql.conf):

wal_level = replica
archive_mode = on
archive_command = 'test ! -f /backups/wal/%f && cp %p /backups/wal/%f'

In production, use a purpose-built tool such as pgBackRest or Barman rather than a hand-rolled cp -- they handle retention, compression, verification, and cloud storage for you.

3. To recover to a moment in time, restore the base backup into an empty data directory and tell Postgres where the WAL is and when to stop:

# postgresql.conf (or postgresql.auto.conf) in the restored cluster
restore_command = 'cp /backups/wal/%f %p'
recovery_target_time = '2026-11-20 14:46:00'
recovery_target_action = 'promote'

Then create an empty file named recovery.signal in the data directory and start the server. Postgres replays the log up to 2:46 PM -- one minute before the mistake -- and opens for business.

Incremental backups (PostgreSQL 17 and newer): pg_basebackup can take an incremental backup against a previous one (--incremental=/path/to/previous/backup_manifest, with summarize_wal = on), and pg_combinebackup stitches the chain into a full backup for restore. This drastically shrinks the nightly backup of a large database.


MySQL and MariaDB: mysqldump

The workhorse logical backup:

mysqldump --single-transaction --routines --triggers --events \
  --all-databases > full_2026-11-20.sql

On MariaDB, the client is named mariadb-dump (with mysqldump kept as a compatibility alias in many installs).

# Restore
mysql < full_2026-11-20.sql

# Restore one database from a dump of many
mysql --one-database myapp < full_2026-11-20.sql

For large databases, use a faster tool:

mysqlsh admin@localhost -- util dump-instance /backups/mysql_2026-11-20 --threads=8
mysqlsh admin@localhost -- util load-dump /backups/mysql_2026-11-20 --threads=8

(Loading may require local_infile to be enabled on the target server.)

Point-in-time recovery works the same way in spirit as Postgres: restore the last full backup, then replay the binary log up to just before the disaster:

mysqlbinlog --stop-datetime="2026-11-20 14:46:00" binlog.000123 | mysql

This requires binary logging to be enabled before you need it.


Microsoft SQL Server: BACKUP and RESTORE

SQL Server's backups are built into T-SQL and are physical by nature. What you can do depends on the database's recovery model:

Recovery model Log backups? Point-in-time restore?
SIMPLE No No -- only to the last full/differential backup
FULL Yes Yes
BULK_LOGGED Yes Mostly (limited around bulk operations)

Full, differential, and log backups:

-- Full backup (compressed, with checksums, and progress messages)
BACKUP DATABASE Sales
  TO DISK = N'D:\Backups\Sales_full.bak'
  WITH COMPRESSION, CHECKSUM, INIT, STATS = 10;

-- Differential: only what changed since the last full backup
BACKUP DATABASE Sales
  TO DISK = N'D:\Backups\Sales_diff.bak'
  WITH DIFFERENTIAL, COMPRESSION, CHECKSUM, INIT;

-- Transaction log backup (FULL or BULK_LOGGED recovery model only)
BACKUP LOG Sales
  TO DISK = N'D:\Backups\Sales_log_1445.trn'
  WITH COMPRESSION, CHECKSUM;

A typical schedule is a weekly full, a daily differential, and a log backup every 5 to 15 minutes. The log backups are what let you lose minutes of data instead of a day.

Check before you trust it:

RESTORE VERIFYONLY FROM DISK = N'D:\Backups\Sales_full.bak' WITH CHECKSUM;

VERIFYONLY confirms the backup is readable and complete, but it does not prove the data restores into a working database. A real test restore still does.

Restoring, including to a point in time. Restore the full backup WITH NORECOVERY (so more backups can follow), then any differential, then the logs, and finish with RECOVERY:

RESTORE DATABASE Sales_Test
  FROM DISK = N'D:\Backups\Sales_full.bak'
  WITH MOVE 'Sales'     TO N'D:\Data\Sales_Test.mdf',
       MOVE 'Sales_log' TO N'D:\Data\Sales_Test_log.ldf',
       NORECOVERY, STATS = 10;

RESTORE DATABASE Sales_Test FROM DISK = N'D:\Backups\Sales_diff.bak' WITH NORECOVERY;

RESTORE LOG Sales_Test FROM DISK = N'D:\Backups\Sales_log_1445.trn'
  WITH STOPAT = '2026-11-20T14:46:00', RECOVERY;

Notes:


SQLite: Don't Just Copy the File

SQLite is a single file, which tempts people to cp app.db backup.db. Don't do this on a live database -- a copy taken mid-write can be corrupt, and in WAL mode the recent changes live in a separate -wal file. Use the tools built for it:

# The online backup command -- safe while the app is running
sqlite3 app.db ".backup 'app_backup.db'"

# Or: a compacted, consistent copy via SQL
sqlite3 app.db "VACUUM INTO 'app_backup.db'"

# Or: a portable text dump
sqlite3 app.db .dump > app_dump.sql

More on the engine itself in SQLite.


Automate It (Because You Will Forget)

A backup that depends on someone remembering is a backup that stops happening. A simple nightly script with cron:

#!/usr/bin/env bash
set -euo pipefail

DB=myapp
DIR=/backups/postgres
STAMP=$(date +%F)

pg_dump -Fc -f "$DIR/${DB}_${STAMP}.dump" "$DB"

# Keep 14 days locally
find "$DIR" -name "${DB}_*.dump" -mtime +14 -delete

# Copy off-site (rclone, aws s3 cp, rsync -- your choice)
rclone copy "$DIR/${DB}_${STAMP}.dump" remote:db-backups/
# crontab -e   -- run at 2:15 AM every night
15 2 * * * /usr/local/bin/backup_myapp.sh >> /var/log/backup_myapp.log 2>&1

Details that matter:


The Only Test That Counts: Restore It

Backups fail in quiet ways -- an empty file, a missing role, a dump that errored halfway, a key that was never saved. The only proof a backup works is restoring it. On a schedule:

  1. Restore the latest backup into a scratch database (or a scratch server).
  2. Run sanity checks -- row counts on key tables, the newest timestamp in an activity table, a handful of known records.
  3. Time it. If the restore takes six hours, that's your real downtime, no matter what you promised the business.
  4. Write down the steps. At 3 AM, you want a checklist, not a memory.
createdb restore_test
pg_restore -d restore_test -j 4 myapp_2026-11-20.dump
psql restore_test -c "SELECT count(*), max(created_at) FROM orders;"
dropdb restore_test

Common Mistakes to Avoid

Mistake Why it hurts Fix
Backups stored on the same server Dies with the disk, the VM, or the ransomware Copy off-site; keep one immutable copy
Never testing a restore You find out it's broken when it matters Scheduled restore tests
cp on a live SQLite or data directory Silent corruption .backup, pg_basebackup, XtraBackup
Forgetting roles/globals (Postgres) Restore succeeds but nothing has permissions pg_dumpall --globals-only
mysqldump without --single-transaction Locks tables or gives an inconsistent snapshot Always use it for InnoDB
SQL Server in FULL recovery with no log backups The log grows until the disk fills, and you can't do point-in-time restores Schedule log backups (or use SIMPLE if you truly don't need them)
Restoring SQL Server with RECOVERY too early No further differentials or logs can be applied Use NORECOVERY until the last step
No binary logs / WAL archive Can only recover to the last dump Enable them before the disaster
Backup job fails silently Months of "backups" that don't exist Alert on missing or tiny files
Lost encryption key The backup is unreadable forever Store keys separately and test decryption

Your Takeaway

  1. Pick your targets: how much data can you afford to lose (RPO), and how long can you be down (RTO)? Those two numbers choose your tools.
  2. Small database? A nightly pg_dump -Fc or mysqldump --single-transaction, copied off-site, covers a lot.
  3. Large or critical? Physical backups plus WAL/binlog/transaction-log archiving for point-in-time recovery (pg_basebackup + WAL, XtraBackup + binlogs, or SQL Server full + differential + log backups).
  4. Automate, encrypt, and monitor it.
  5. Restore it regularly. Not "someday" -- on a calendar.

The best time to find out your backup works was last month. The second-best time is today. Go restore something.

What did you learn?

Tell us what you learned from this article, or what you liked about it. We read every comment.

Comments appear after a quick review. Please no links.

Know someone who'd love it too?

Most covered topics