How to Restore a MySQL Database (Complete Guide: mysqldump, GUI Tools, and Binary Logs)

目次

1. Introduction

What Is a MySQL Restore?

A MySQL restore is the process of recovering backed-up data into the original database.
By performing a restore, you can recover data after data loss or system failures and continue operating your business or system.

Databases can become corrupted or lost for various reasons. For example, the following cases are common:

  • Server crashes or hardware failures
  • Accidental data deletion
  • Data corruption caused by updates or system changes
  • Data loss due to malware or external attacks

To prepare for these situations, it is important to take proper backups in advance.
Then, by restoring at the necessary time, you can recover your system quickly.

What You Will Learn in This Article

This article explains MySQL restore procedures in detail.
To support everyone from beginners to advanced users, it introduces everything from basic restore methods to advanced recovery techniques.
Specifically, you will learn the following:

  • Basic MySQL restore steps
  • How to restore using the command line (mysqldump)
  • Restoring with GUI tools (phpMyAdmin, MySQL Workbench)
  • How to restore only specific data
  • Optimizing restores for large datasets
  • Advanced recovery using binary logs
  • How to verify data after a restore
  • Troubleshooting when errors occur

By following this guide, you will be able to design an appropriate backup strategy and restore quickly when needed.
From the next section, we will explain the preparations required before performing a restore.

2. Preparation Before Restoring

Types of MySQL Backups

To perform a restore, it is important to create proper backups in advance. MySQL backup methods include the following types:

1. Backup Using mysqldump

mysqldump is a tool that exports a MySQL database in SQL format. It is the most common method and is easy to restore.

mysqldump -u username -p database_name > backup.sql

Because this method saves data as a text file, it is easy to edit, but it is not suitable for very large datasets.

2. Backup Using phpMyAdmin

This method uses phpMyAdmin’s GUI to create a backup easily. You can export it as an SQL file.

  1. Log in to phpMyAdmin
  2. Select the “Export” tab
  3. Set the format to “SQL” and click “Go”

This method is beginner-friendly but not suitable for large-scale data.

3. Backup Using MySQL Workbench

MySQL Workbench can create backups via a GUI. Using the Data Export feature, you can export specific databases or tables.

4. Backup Using Binary Logs

Using binary logs lets you record changes up to a specific point in time, enabling data recovery.

mysqlbinlog --start-datetime="2024-02-01 10:00:00" --stop-datetime="2024-02-01 12:00:00" binlog.000001 > restore.sql

This method enables advanced recovery, but it requires proper log management.

Pre-Restore Checklist

To successfully restore, you need to confirm the following points in advance.

1. Confirm the Character Set (UTF-8 vs. SJIS)

If the character set differs between backup time and restore time, text may become garbled. Check the encoding of the backup file.

file backup.sql

Also, specifying --default-character-set=utf8mb4 during restore can help avoid character set issues.

mysql -u username -p --default-character-set=utf8mb4 database_name < backup.sql

2. Create the Target Database for Restore

Before restoring, confirm whether the target database exists. If it does not, create it.

mysql -u username -p -e "CREATE DATABASE IF NOT EXISTS database_name;"

3. Check Backup File Integrity

To confirm the backup file is not corrupted, try displaying part of its contents.

head -n 20 backup.sql

If the file size is unusually small, the backup may not have been created correctly.

How to Choose a Restore Method (Comparison Table)

The restore method depends on your environment and data size. Use the table below to choose the most suitable option.

MethodDifficultyProsCons
mysqldumpIntermediateFast and highly reliableRequires manual commands
phpMyAdminBeginnerEasy to operate via GUINot suitable for large datasets
WorkbenchBeginnerSimple UI workflowCan put high load on the server
Binary logAdvancedPoint-in-time recovery possibleComplex configuration

3. MySQL Database Restore Procedures

Restoring a Single Database

How to Restore a mysqldump Backup

The most common restore method is to recover backup data created with mysqldump.

Steps:

  1. Verify the backup file is correct
   head -n 20 backup.sql

→ Check the beginning of the backup file and confirm there are no errors.

  1. Create the target database (if it does not exist)
   mysql -u username -p -e "CREATE DATABASE IF NOT EXISTS database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
  1. Restore the data
   mysql -u username -p database_name < backup.sql

Specifying Options to Prevent Garbled Characters

If the data encoding differs, you may see garbled characters during restore.
To prevent this, it is common to specify --default-character-set=utf8mb4.

mysql -u username -p --default-character-set=utf8mb4 database_name < backup.sql

Notes:

  • Confirm the character set used at backup time matches the one used at restore time
  • Set the database default character set to UTF-8 (utf8mb4) when creating the database
  CREATE DATABASE database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Restoring Multiple Databases

If the backup file contains multiple databases, you can restore them by running the import without specifying a database (commonly used with dumps created using --databases).

mysql -u username -p < backup.sql

If you want to restore only a specific database, run the following:

mysql -u username -p --one-database target_database_name < backup.sql

Example:

mysql -u root -p --one-database sales_db < all_databases_backup.sql

→ Restores only sales_db.

Restoring All Databases

To restore all databases at once, use --all-databases.

mysql -u username -p --all-databases < backup.sql

Key points:

  • Using --all-databases restores all databases in the backup file.
  • It is important to check in advance whether the file contains statements like DROP DATABASE or CREATE DATABASE.
  • If you have a large amount of data, optimize memory settings (details are explained in “5. Restore Optimization for Large Datasets”).

Restoring with GUI Tools

Restore Using phpMyAdmin

  1. Log in to phpMyAdmin
  2. Select the “Import” tab
  3. Select and upload the backup file (SQL)
  4. Click “Go” to start the restore

Pros:

  • Easy to operate for beginners
  • You can restore without using command-line tools

⚠️ Cons:

  • File size limits may apply
  • Not suitable for large-scale data

Restore Using MySQL Workbench

  1. Open MySQL Workbench
  2. Select “Server > Data Import”
  3. Select the backup file
  4. Specify the target database
  5. Click “Start Import” to run the restore

Pros:

  • Intuitive GUI workflow
  • You can restore only specific tables

⚠️ Cons:

  • May put high load on the server
  • Watch for compatibility with your MySQL Server version

4. How to Verify Data After a MySQL Restore

Basic Commands to Confirm a Successful Restore

1. Check the List of Databases

After restoring, confirm that the databases were created correctly.

SHOW DATABASES;

Checkpoints

  • Are all databases included in the backup file displayed?
  • Is the restore target database name correct?

2. Check the List of Tables in Each Database

Even if the database exists, it is useless if the tables were not restored correctly.
Use the following commands to check the list of tables in the database.

USE database_name;
SHOW TABLES;

Checkpoints

  • Are all required tables displayed?
  • Depending on mysqldump options, were any tables accidentally omitted?

3. Check Row Counts in Tables

Even after the restore finishes, you can verify whether data was restored properly using COUNT(*).

SELECT COUNT(*) FROM table_name;

Checkpoints

  • Does the COUNT(*) result match the row count before the backup?
  • Is any data missing?
  • Are there unusually many NULL or 0 values?

4. Verify That Specific Data Was Restored Correctly

To ensure data was restored correctly, extract and inspect a few rows.

SELECT * FROM table_name LIMIT 10;

Checkpoints

  • Are the ordering and values normal?
  • Is there any garbled text?

Checking for Garbled Characters and Data Corruption

If the character encoding is not handled properly during restore, text may become garbled.
To prevent this problem, check character encoding after the restore.

1. Check the Database Encoding

SELECT SCHEMA_NAME, DEFAULT_CHARACTER_SET_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME='database_name';

2. Check the Table Encoding

SHOW CREATE TABLE table_name;

💡 Tips to prevent garbled characters

  • When exporting with mysqldump, specify --default-character-set=utf8mb4
  • When restoring, also specify --default-character-set=utf8mb4
  • Edit the SET NAMES settings inside the backup file if needed

Verify Index and Foreign Key Integrity

1. Check Whether Indexes Are Set Correctly

SHOW INDEX FROM table_name;

Checkpoints

  • Were indexes restored correctly?
  • Did queries on specific columns become unusually slow?

2. Check Foreign Key Constraints

If you restore tables with foreign key constraints, you must confirm the constraints are applied correctly.

SELECT TABLE_NAME, CONSTRAINT_NAME, REFERENCED_TABLE_NAME 
FROM information_schema.KEY_COLUMN_USAGE 
WHERE TABLE_SCHEMA = 'database_name';

Checkpoints

  • Were all foreign key constraints restored?
  • Are settings such as ON DELETE CASCADE and ON UPDATE CASCADE correct?

Check Log Files to Investigate Restore Issues

If errors occur during restore, you can identify the problem by checking MySQL error logs.

1. Check MySQL Error Logs

sudo cat /var/log/mysql/error.log

What to look for in error logs

  • ERROR 1366 (HY000): Incorrect string value → Possible encoding issue
  • ERROR 1452 (23000): Cannot add or update a child row → Foreign key constraint error
  • ERROR 2006 (HY000): MySQL server has gone away → Backup file may be too large

Performance Optimization After Restoring

After a restore, it is important to verify not only data integrity but also performance impact.

1. Check Query Execution Speed

If data searches become slow after restore, indexes may not have been restored properly.

EXPLAIN SELECT * FROM table_name WHERE column_name = 'value';

2. Optimize Tables

To reduce fragmentation and improve performance, optimize tables.

OPTIMIZE TABLE table_name;

3. Clear Caches

If a large amount of data was restored, clearing caches temporarily may improve performance.

RESET QUERY CACHE;

Summary

To confirm that restored data is correct, the following steps are important:

Basic database and table checks
Verify row counts and check for garbled characters
Validate indexes and foreign keys
Analyze error logs to identify issues
Apply performance optimizations

A database restore is not complete just by applying a backup; it is complete only after integrity checks and operational verification.

5. Restore Optimization for Large Datasets

Adjusting the max_allowed_packet Setting

1. What Is max_allowed_packet?

MySQL limits the maximum packet size that can be sent at once using the max_allowed_packet setting.
If this value is too small, errors may occur when restoring large SQL queries.

2. Check the Current Setting

SHOW VARIABLES LIKE 'max_allowed_packet';

The default value is typically 16MB (16,777,216 bytes). When restoring large datasets, increasing it to 256MB or higher is recommended.

3. Change the Setting Temporarily

To modify it temporarily within a MySQL session:

SET GLOBAL max_allowed_packet=268435456;  -- 256MB

4. Change the Setting Permanently

Edit the MySQL configuration file (my.cnf or my.ini) and add or modify the following line:

[mysqld]
max_allowed_packet=256M

After making changes, restart MySQL:

sudo systemctl restart mysql

Checkpoints

  • If you see ERROR 2006 (HY000): MySQL server has gone away, increase max_allowed_packet.
  • If restore fails midway when handling large data, review this setting.

Optimizing innodb_buffer_pool_size

1. What Is innodb_buffer_pool_size?

innodb_buffer_pool_size determines how much memory the InnoDB storage engine uses.
If the value is too small, restore operations frequently access disk, reducing performance.

2. Check the Current Setting

SHOW VARIABLES LIKE 'innodb_buffer_pool_size';

The default value is typically around 128MB. For large datasets, allocating 50–70% of total server memory is recommended.

3. How to Configure

Edit my.cnf and add or modify the following line:

[mysqld]
innodb_buffer_pool_size=2G

Then restart MySQL:

sudo systemctl restart mysql

Checkpoints

  • If sufficient server memory is available, increasing innodb_buffer_pool_size improves restore speed.
  • In smaller environments, monitor memory usage carefully when adjusting.

Partitioning to Improve Restore Speed

1. Benefits of Partitioning

As a database grows, a single table may contain a large volume of data, increasing restore load.
By dividing a table into partitions, restore performance can be improved.

2. Example Partition Configuration

For example, to partition by the created_at date:

CREATE TABLE orders (
    id INT NOT NULL,
    created_at DATE NOT NULL,
    PRIMARY KEY (id, created_at)
) PARTITION BY RANGE (YEAR(created_at)) (
    PARTITION p2023 VALUES LESS THAN (2024),
    PARTITION p2024 VALUES LESS THAN (2025)
);

This also allows you to restore specific partitions only.

Checkpoints

  • Instead of restoring all data at once, splitting by partition can significantly improve performance.
  • Design tables with partitioning in mind to better manage large datasets.

Faster Restore Using --disable-keys

1. What Is --disable-keys?

When inserting large volumes of data into indexed tables, MySQL updates indexes for each insert, slowing down restore operations.
Using DISABLE KEYS temporarily suspends index updates and speeds up the restore.

2. How to Use It

  1. Edit the backup file and add the following line:
ALTER TABLE table_name DISABLE KEYS;
  1. Run the restore process
mysql -u username -p database_name < backup.sql
  1. After restore completes, re-enable indexes:
ALTER TABLE table_name ENABLE KEYS;

Checkpoints

  • Using DISABLE KEYS significantly improves restore speed for large inserts.
  • Do not forget to run ENABLE KEYS after restore.

6. Troubleshooting MySQL Restore Issues

Common Error Messages and Solutions

1. “Unknown Database” Error

Error Message

ERROR 1049 (42000): Unknown database 'database_name'

Cause

  • The target database was not created before running the restore.

Solution

  1. Create the database manually
   mysql -u username -p -e "CREATE DATABASE database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
  1. Run the restore again
   mysql -u username -p database_name < backup.sql

2. “Incorrect String Value” (Garbled Characters)

Error Message

ERROR 1366 (HY000): Incorrect string value

Cause

  • Character set mismatch between backup and restore
  • Improper database default character set

Solution

  1. Check the encoding of the backup file
   file backup.sql
  1. Specify --default-character-set=utf8mb4 when restoring
   mysql -u username -p --default-character-set=utf8mb4 database_name < backup.sql
  1. Unify the database character set
   ALTER DATABASE database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
   ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

3. “MySQL Server Has Gone Away” During Restore

Error Message

ERROR 2006 (HY000): MySQL server has gone away

Cause

  • Backup file is too large
  • max_allowed_packet is too small
  • MySQL crashes due to insufficient memory

Solution

  1. Increase max_allowed_packet
   SET GLOBAL max_allowed_packet=256M;
  1. Adjust innodb_buffer_pool_size
   [mysqld]
   innodb_buffer_pool_size=2G
  1. Compress the backup before restoring
   mysqldump -u username -p database_name | gzip > backup.sql.gz
   gunzip < backup.sql.gz | mysql -u username -p database_name
  1. Split the SQL file
   split -b 500M backup.sql backup_part_

Restore split files sequentially:

   cat backup_part_* | mysql -u username -p database_name

Handling Large Backup Files

1. Split the SQL File Before Restoring

If the data to restore is too large, splitting the file into smaller chunks increases the success rate.

split -b 500M backup.sql backup_part_

Restore the split files sequentially:

cat backup_part_* | mysql -u username -p database_name

2. Use the --single-transaction Option with mysqldump

This option performs the dump within a single transaction, reducing locking and lowering load when restoring large datasets.

mysqldump --single-transaction -u username -p database_name > backup.sql

3. Temporarily Disable innodb_flush_log_at_trx_commit

Reducing transaction log write frequency during large restores can significantly improve restore speed.

SET GLOBAL innodb_flush_log_at_trx_commit=0;

After the restore, do not forget to revert to the original setting (default: 1).

SET GLOBAL innodb_flush_log_at_trx_commit=1;

Check Log Files to Investigate Restore Issues

1. Review MySQL Error Logs

If the restore fails, reviewing the MySQL error log helps identify the root cause.

sudo cat /var/log/mysql/error.log

2. Use SHOW WARNINGS; to Display Detailed Messages

SHOW WARNINGS;

Common Warnings

MessageCauseSolution
Duplicate entryPrimary key duplicationUse INSERT IGNORE
Table already existsThe table already existsRun DROP TABLE IF EXISTS before restore
Data truncated for columnString exceeds column limitIncrease VARCHAR size

7. Frequently Asked Questions (FAQ)

Q1: What should I do if I see “Unknown database” during restore?

Error Message

ERROR 1049 (42000): Unknown database 'database_name'

Cause

  • The backup file does not contain a CREATE DATABASE statement
  • The specified database does not exist at restore time

Solution

  1. Create the database manually
   mysql -u username -p -e "CREATE DATABASE database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
  1. Run the restore again
   mysql -u username -p database_name < backup.sql

Q2: How can I fix garbled characters after restore?

Error Message

ERROR 1366 (HY000): Incorrect string value

Cause

  • Character set mismatch between backup and restore
  • Improper default database character set

Solution

  1. Check backup file encoding
   file backup.sql
  1. Specify --default-character-set=utf8mb4 during restore
   mysql -u username -p --default-character-set=utf8mb4 database_name < backup.sql
  1. Unify the database character set
   ALTER DATABASE database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
   ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Q3: How do I restore a large SQL file (1GB or more)?

Issues

  • Restore takes a long time
  • ERROR 2006 (HY000): MySQL server has gone away

Solutions

  1. Increase max_allowed_packet
   SET GLOBAL max_allowed_packet=256M;
  1. Adjust innodb_buffer_pool_size
   [mysqld]
   innodb_buffer_pool_size=2G
  1. Compress the backup before restoring
   mysqldump -u username -p database_name | gzip > backup.sql.gz
   gunzip < backup.sql.gz | mysql -u username -p database_name
  1. Split the SQL file
   split -b 500M backup.sql backup_part_

Restore sequentially:

   cat backup_part_* | mysql -u username -p database_name

Q4: How do I restore in AWS RDS (cloud environment)?

Steps

  1. Create a local backup
   mysqldump -u username -p --databases database_name > backup.sql
  1. Transfer the backup file to the AWS RDS instance
   scp backup.sql username@server_ip:/path/to/backup/
  1. Connect to AWS RDS and restore
   mysql -h rds_endpoint -u username -p database_name < backup.sql

Important

  • Since AWS RDS does not provide SUPER privileges, specify --set-gtid-purged=OFF when creating the backup.
   mysqldump -u username -p --set-gtid-purged=OFF --databases database_name > backup.sql

Q5: How can I automatically test backups and restores?

Solution
Use a Linux cron job to automatically perform daily backups and restore tests.

1. Automated Backup Script

#!/bin/bash
BACKUP_DIR="/var/backups/mysql"
DATE=$(date +"%Y%m%d")
DB_NAME="your_database"
USER="your_user"
PASSWORD="your_password"

# Create backup
mysqldump -u $USER -p$PASSWORD $DB_NAME > $BACKUP_DIR/backup_$DATE.sql

# Delete backups older than 30 days
find $BACKUP_DIR -type f -name "backup_*.sql" -mtime +30 -exec rm {} \;

2. Automated Restore Test Script

#!/bin/bash
DB_NAME="restore_test"
USER="your_user"
PASSWORD="your_password"
BACKUP_FILE="/var/backups/mysql/backup_latest.sql"

# Create test database
mysql -u $USER -p$PASSWORD -e "DROP DATABASE IF EXISTS $DB_NAME; CREATE DATABASE $DB_NAME;"

# Execute restore
mysql -u $USER -p$PASSWORD $DB_NAME < $BACKUP_FILE

3. Add to Cron Job

crontab -e

Add the following lines (backup at 3:00 AM, restore test at 4:00 AM daily):

0 3 * * * /path/to/backup_script.sh
0 4 * * * /path/to/restore_test_script.sh

Checkpoints

  • Perform automated backup and restore tests regularly
  • Continuously verify backup file integrity

8. Conclusion

Review of Basic MySQL Restore Procedures

Preparation Before Restore

  • Understand backup types (mysqldump, phpMyAdmin, binary logs, etc.)
  • Verify database existence and character sets before restore
  • Select the appropriate restore method

MySQL Restore Methods

MethodDifficultyProsCons
mysqldumpIntermediateFast and versatileRequires command-line operations
phpMyAdminBeginnerEasy GUI operationNot suitable for large datasets
WorkbenchBeginnerSimple UI workflowHigh server load
Binary logAdvancedPoint-in-time recovery possibleComplex configuration

Post-Restore Verification

  • Use SHOW DATABASES; to confirm databases were created
  • Use SHOW TABLES; to confirm tables were restored
  • Use SELECT COUNT(*) to verify row counts
  • Use SHOW WARNINGS; to check for restore warnings

Optimization for Large Dataset Restores

  • Adjust max_allowed_packet and innodb_buffer_pool_size
  • Split backup files before restoring (split -b 500M backup.sql backup_part_)
  • Use DISABLE KEYS to optimize index rebuilding

Troubleshooting During Restore

  • “Unknown database” → Run CREATE DATABASE
  • “Garbled characters” → Specify --default-character-set=utf8mb4
  • “Restore stops midway” → Increase max_allowed_packet
  • “Large data restore” → Split files or use --single-transaction
  • “AWS RDS restore” → Use --set-gtid-purged=OFF
  • Check logs → Use SHOW WARNINGS;

Best Practices for Backup and Restore Operations

Properly managing backups and restores minimizes the risk of data loss.
By performing regular backups and restore tests, you can recover data smoothly in case of actual system failures.

1. Schedule Regular Backups

  • Schedule daily or weekly backups
  • Combine full backups with incremental backups
  • Store backups locally and remotely
  • Local: /var/backups/mysql/
  • Cloud storage (S3, Google Drive, FTP)

2. Automate Backup Scripts

Automating backups reduces human error and prevents missed backups.

#!/bin/bash
BACKUP_DIR="/var/backups/mysql"
DATE=$(date +"%Y%m%d")
DB_NAME="your_database"
USER="your_user"
PASSWORD="your_password"

# Create backup
mysqldump -u $USER -p$PASSWORD $DB_NAME > $BACKUP_DIR/backup_$DATE.sql

# Delete backups older than 30 days
find $BACKUP_DIR -type f -name "backup_*.sql" -mtime +30 -exec rm {} \;

3. Automated Restore Testing

It is important to regularly test whether backups can actually be restored.

#!/bin/bash
DB_NAME="restore_test"
USER="your_user"
PASSWORD="your_password"
BACKUP_FILE="/var/backups/mysql/backup_latest.sql"

# Create test database
mysql -u $USER -p$PASSWORD -e "DROP DATABASE IF EXISTS $DB_NAME; CREATE DATABASE $DB_NAME;"

# Execute restore
mysql -u $USER -p$PASSWORD $DB_NAME < $BACKUP_FILE

4. Monitoring and Alerts

  • Receive notifications if backups fail
  • Set MAILTO in cron
  • Use Slack or email notifications
MAILTO="your_email@example.com"
0 3 * * * /path/to/backup_script.sh

Ensuring Successful MySQL Restores

Backup and restore processes are critical components of data protection.
Especially in business operations and development environments, regular backups and restore testing are essential.

Use the procedures introduced in this article to improve your MySQL backup and restore operations.

🔹 MySQL Restore Success Checklist

Are backups taken regularly?
Have you verified the contents of backup files in advance?
Do you perform integrity checks after restore?
Are large dataset restore settings properly configured?
Do you have troubleshooting procedures prepared?
Have you automated backup and restore processes?

Next Steps

Based on this article, test your MySQL restore process and confirm successful recovery.
Also, document your restore procedures and share them with your team.

Continuously improve your backup and restore operations to protect your data! 🚀