Back up a SQLite database and prove the backup restores
Learn to back up a SQLite database safely and verify that the copy restores with matching data.
A SQLite database is a database that lives in a single file on your disk, with no separate server program running. If that file is corrupted or deleted, your data is gone unless you have a backup. Copying the file while a program is writing to it can give you a broken copy, so use the built-in backup command instead.
Back up the database with the sqlite3 tool
- Open a terminal or command prompt — the text-based program where you type commands.
- Change to the folder that contains your database file.
- Run this command, replacing
mydatabase.dbwith your file name:
sqlite3 mydatabase.db ".backup mydatabase-backup.db"
The .backup part is a dot command: an instruction to the sqlite3 program, not an SQL query. It tells SQLite to lock the database, copy it safely, and close it.
Think of it like photocopying a ledger while the office is closed, so no one is half-way through writing a number when you take the picture.
Reference: Command line shell for SQLite
Check the backup contains your data
Run these commands on the backup file:
sqlite3 mydatabase-backup.db ".tables"
sqlite3 mydatabase-backup.db "SELECT count(*) FROM yourtable;"
Replace yourtable with a real table name from your database. Write down the number it returns.
Reference: SELECT statement
Prove the restore works
- Copy the backup to a new file:
- macOS or Linux:
cp mydatabase-backup.db mydatabase-restored.db - Windows:
copy mydatabase-backup.db mydatabase-restored.db
- macOS or Linux:
- Open the restored file and run the same count query:
sqlite3 mydatabase-restored.db "SELECT count(*) FROM yourtable;"
- Compare the number with the one from the backup. If they match, the backup restored correctly.
Reference: Command line shell for SQLite
Expected result
You should see three files: your original database, the backup, and the restored copy. The row count from the backup and the restored copy should be identical. If the restored file opens and returns the same count, your backup works.
Sources
Stay Ahead. Work Smarter.
Get practical AI tips, automation ideas and useful technology tricks — one useful thing at a time. Follow the feed in any reader.