Back Up a Database and Restore It to a New Database

Export the practice database to SQL, restore it to a new database, and verify the records

🎯 Introduction

By the end of this article, you will be able to save a database's tables and data to a file and use that file to restore them in a new database.

Suppose Xiao Ming was in the user table when you backed up yesterday. Even if you accidentally delete Xiao Ming and commit today, yesterday's backup still contains the record. A backup preserves past data; restoring writes that saved content back into a database.

However, data added or changed after yesterday's backup does not automatically appear in yesterday's file.


💾 What a backup file contains

This article uses MySQL's bundled mysqldump tool. It writes table creation and data insertion statements to a .sql file. Executing that file later recreates the tables and fills them with the data from that time.

Name in this articleWhat it isPurpose
blog_demoExisting practice databaseSupplies the tables and data to back up
blog-demo.sqlExported backup fileStores SQL for creating tables and inserting data
blog_restoreNew database created belowReceives restored data for verification

The volume from the getting-started article holds live data, so accidental deletions change it too. A backup file preserves a copy from another point in time. Keeping the volume does not replace backups.

This exercise only exports the original database and imports into a new one. You do not need to delete any original data.


🔎 Record the data you will verify first

Stop scripts or services that read and write the practice database so the data remains unchanged and easy to compare. Open a terminal and log in to the original database:

docker exec -it mysql-course mysql -uroot -p blog_demo

Enter the root password, then query the user table at mysql>:

SELECT id, username FROM user ORDER BY id;

If you retained the three users from the CRUD article, the result is:

idusername
1Xiao Ming
2Xiao Hong
3Xiao Gang

Record your actual query result and compare against it after restoration. Your practice data need not match this example exactly. Then enter exit to return to the terminal.


📤 Export the practice database to a file

Run the following in your terminal. A trailing backslash continues the command onto the next line; execute the whole block together:

docker exec -it mysql-course mysqldump -uroot -p \
    --single-transaction --no-tablespaces --set-gtid-purged=OFF \
    --result-file=/tmp/blog-demo.sql blog_demo

After you enter the root password, the tool writes blog_demo's schema and data to /tmp/blog-demo.sql inside the container. It writes data to the file instead of printing the entire table. Successful completion returns you to the terminal prompt.

The command's options control the following:

OptionPurpose in this backup
-uroot -pLog in as root and enter the password when prompted
--single-transactionExport the course's InnoDB tables from a consistent committed snapshot at the start of the backup
--no-tablespacesOmit the server's data-file organization configuration, which is unnecessary for restoring these tables and records
--set-gtid-purged=OFFOmit transaction identifier settings used to synchronize multiple MySQL servers; this exercise restores only practice data
--result-file=/tmp/blog-demo.sqlSpecify the export file's path inside the container
blog_demoSelect the database to back up

Do not add columns, drop tables, or perform other schema changes during the backup. This local exercise uses root without putting the password in the command.

If the terminal reports an error, resolve it and export again. A generated file alone does not prove the backup succeeded. Repeating the command overwrites this file; use different filenames to retain multiple backups.


📁 Copy the file to your computer

The file is still inside the container. Continue in the terminal:

docker cp mysql-course:/tmp/blog-demo.sql ./blog-demo.sql

This copies it into your terminal's current directory. Open blog-demo.sql in an editor; you should find statements creating the user table and inserting its records.

Content only proves that the file is not empty. You must import it to verify that it can be restored. The file contains user data; do not commit it to a public repository. Keep a real backup outside the database machine too, so a machine or disk failure does not destroy both copies.


🗃 Create a database to receive the restored data

Reopen the MySQL command line from the terminal:

docker exec -it mysql-course mysql -uroot -p

Enter the root password, then create the new database at mysql>:

CREATE DATABASE blog_restore CHARACTER SET utf8mb4;

Success displays Query OK. blog_restore is a new, empty database; utf8mb4 supports characters including Chinese text.

If the database already exists, choose another unused name and use it consistently in subsequent commands. Do not delete an existing database just to repeat the exercise.


📥 Import the backup into the new database

To verify that the copy on your computer works too, enter exit to return to the terminal, then copy that file back into the container under another name:

docker cp ./blog-demo.sql mysql-course:/tmp/blog-restore-input.sql

Open the MySQL command line, specifying the receiving database:

docker exec -it mysql-course mysql -uroot -p blog_restore

After entering the password, execute this at mysql>:

SOURCE /tmp/blog-restore-input.sql;

SOURCE reads the file and executes its SQL statements in sequence. The MySQL client runs inside the container, so use the file's container path here.

The client displays results for table creation and data insertion statements. Resolve any errors and verify again; do not skip errors and assume restoration succeeded. After a successful import, blog_restore contains the tables and data from the backup.

The export specified only blog_demo without the --databases option, which would include a command to switch to the original database. This allows restoration under a different database name. Do not blindly use SQL files from unknown sources: they may specify a different target database.

Backup files may contain statements that drop and recreate tables with the same names. Import this backup into the new blog_restore database, never into the active blog_demo database, to avoid overwriting current data.

✅ Query the restored data to confirm the tables are populated

Continue in the MySQL window connected to blog_restore:

SELECT id, username FROM user ORDER BY id;

If the data before backup was the three rows shown earlier, the restored result should also be:

idusername
1Xiao Ming
2Xiao Hong
3Xiao Gang

Compare against your recorded pre-backup results: IDs and usernames should match. Verify other fields you need to preserve, such as city and age, too. This article shows only two columns to keep the restoration process clear.

This exercise verifies that the file saved on your computer can execute and restore the data we checked into a new database. In a real project, also check other application tables and required constraints, then connect the application to the restored database and run common queries. Matching the user table alone does not prove everything is correct.


🕒 Use the backup after an actual accidental deletion

If you delete Xiao Ming from the original database after the backup, the file remains unchanged. Restoring it into a new database lets you inspect Xiao Ming's record as it existed at backup time and determine which records to recover.

Do not overwrite the entire current database directly with an old backup. It may contain users added after the backup, and a full overwrite would lose that new data. Restore to a separate database, identify the differences, then decide whether to recover a few records or the whole database.

With daily backups, this file cannot recover changes made after the latest backup. Choose a backup frequency based on how much data loss is acceptable, and regularly repeat import verification. Projects needing recovery to a more recent time can use a managed database's point-in-time recovery feature, configured and rehearsed according to the provider's procedure.


❓ Questions and Answers

Q1: Does exporting empty the original database?

No. Exporting reads the original data and generates a file; it does not move the data out.

Q2: Does the backup file update automatically with the database?

No. It preserves data at export time. Later changes require a new backup.

Q3: Why restore into a new database first?

This verifies that the file works while preserving current data in the original database, avoiding an overwrite during backup verification.


🧪 Exercise

Change Xiao Ming's username in blog_restore, then query blog_restore.user and blog_demo.user separately to confirm that the copies are independent. Keep the backup file and import it into another new database to check that Xiao Ming still has the name recorded at backup time.

-- Write your SQL or record your verification results here