Back Up Your Practice Database Before You Experiment
Experimenting is how you learn SQL, and experiments sometimes go wrong: a DELETE without WHERE, a dropped table, a broken migration. A backup turns those moments from disasters into shrugs. Here are simple backup habits for beginners.
The easiest backup of all: rebuild from scripts
If your tables and sample data live in files such as schema.sql and seed.sql, you can always rebuild:
rm practice.db
sqlite3 practice.db < schema.sql
sqlite3 practice.db < seed.sql
For practice work, this is often all you need. It is also the reason I nag every beginner to keep statements in files.
Backing up a SQLite database
Option 1: copy the file while nothing is using it.
cp practice.db practice-backup.db
Close any program connected to the database first, so you do not copy it mid-change.
Option 2: dump to SQL text.
sqlite3 practice.db .dump > practice-backup.sql
This writes CREATE and INSERT statements that rebuild everything. Text files are easy to read and to keep in version control.
Option 3: the built-in backup command. In the sqlite3 tool, .backup practice-backup.db makes a safe copy even if the database is in use.
Backing up PostgreSQL and MySQL
Server databases come with dump tools:
pg_dump -U myuser -d practice > practice-backup.sql
mysqldump -u myuser -p practice > practice-backup.sql
Both create SQL files you can load back into an empty database. They prompt for, or read, your password; avoid typing passwords directly on the command line where they may be saved in your shell history.
A backup you never tested is a hope
Practise restoring at least once:
- Make a backup.
- Create a new, empty practice database.
- Load the backup into it.
- Run a few SELECT queries to check the data is there.
Doing this once on a small practice database means you will know what to do when it really matters.
When to back up
| Before you... | Back up? |
|---|---|
| Try a DELETE or UPDATE you are unsure about | Yes, or use a transaction |
| Run a new migration | Yes |
| Upgrade your database software | Yes |
| Write a SELECT | No need |
Transactions: the instant undo
For a single risky statement, a transaction is quicker than a backup:
BEGIN;
DELETE FROM pets WHERE age > 10;
SELECT COUNT(*) FROM pets;
ROLLBACK; -- or COMMIT if it looks right
See a first look at transactions for more.
Keep backups somewhere sensible
A backup on the same laptop protects you from mistakes, not from a lost laptop. For practice work, that is usually fine. For anything with real value, keep a copy elsewhere, and remember that backups containing personal data must be protected like the database itself.
A free learning page for beginners. Practise on a test database, never on real customer data, and check the official documentation for your database version.