Backup an SQLite Database

The SQLite command line shell provides the .backup dot command that enables you to quickly and easily back up a database.

To use this command, provide the name of the database you want to back up, and a file name for the backup file.

Example

Here’s an example of backing up a database.

.backup Store Store_backup.db

This backs up the database called Store to a backup file called Store_backup.db in the current directory.

To backup to another directory, use the path. For example:

.backup Store /Users/sqlite/bak/Store_backup.db

Backup the Main Database

The first argument is optional. For example, you could connect to SQLite like this:

sqlite3 Chinook.db

Which opens the Chinook.db database. This database will appear as the main database.

Then run this:

.backup Chinook_backup.db

That will back up the database to the specified file.

Backup the Currently Attached Database

Here’s another example that is similar to the previous one, but with a slightly different use case.

In this example, I connect to SQLite without specifying a database. Then I attach a database, then run the .backup command.

I’ll combine all commands for the sake of brevity:

sqlite3
ATTACH DATABASE 'Store.db' AS Store;
.backup Backup.db

This backs up the Store database.

Restore/Use the Backup

You can use the .restore command to restore the database. This accepts the name of the database to restore to, followed by the location of the backup file.

Example:

ATTACH DATABASE 'Chinook2.db' AS Chinook2;
.restore Chinook2 Chinook_backup.db

In this case I created a blank database called Chinook2 with which to restore the backup to.

Another way to do it is to simply attach the backup, just like you’d do with any other database file:

ATTACH DATABASE 'Chinook_backup.db' AS Chinook;

If you use this method, you’ll probably want to take a copy of your back ups and only attach the copy. Otherwise you’ll overwrite your backup and there will be no ability to restore it back to an earlier version.