MySQL mysqldump –single-transaction Explained: Consistent Backups Without Locking Tables

目次

1. The Importance of Backups for Maintaining Database Consistency

Database Backups Are “Insurance”

In business, the database can be considered the heart of operations. Customer information, transaction history, inventory data—nearly every business process depends on the database. If data is lost due to system failure or human error, it can lead to serious risks such as operational downtime and loss of trust.
For this reason, regular backups are an essential operational “insurance policy.”

How Do You Ensure Data Consistency During Backups?

However, one of the major challenges when performing backups is ensuring “consistency” (data integrity). Especially when you want to back up a system without stopping it while it is running, maintaining consistency becomes critically important.

For example, if someone updates a table during the backup process, discrepancies may occur between the dumped data and the actual state of the database.

What Is mysqldump? And What Is –single-transaction?

The widely used backup tool for MySQL and MariaDB is mysqldump. With simple command-line operations, you can export an entire database or specific tables into an SQL file.

The option used to safely and efficiently maintain backup consistency in mysqldump is the focus of this article: --single-transaction.

This option uses transactions (units of work) to preserve a “snapshot of a specific point in time” while allowing backups to proceed without blocking other processes. It is an extremely useful feature.

What You Will Learn in This Article

In this article, we thoroughly explain how to use the mysqldump --single-transaction option, important considerations, and how to combine it with other options from a practical perspective.

  • Those who want to understand the basics of mysqldump
  • Those who want to correctly understand the meaning of --single-transaction
  • Those who want to implement safe backup operations in real-world environments

We will walk through practical command examples in a clear and easy-to-understand way. Be sure to read through to the end.

2. Basic Usage of mysqldump

What Is mysqldump?

mysqldump is the standard command-line tool for backing up MySQL and MariaDB databases. It exports table structures and data in SQL format, and restoring is as simple as executing the SQL file to return the database to its original state.

It is both convenient and powerful, and widely used in development and production environments alike.

Basic mysqldump Syntax

The following is the simplest form of the mysqldump command:

mysqldump -u username -p database_name > output_file.sql
  • -u: Username used to log in to MySQL
  • -p: Prompts for password input (cannot be omitted)
  • database_name: The database to back up
  • >: Specifies the output file (redirect)

After running the command, you will be prompted for a password. If successful, an SQL-format backup file will be generated.

Backing Up Specific Tables Only

If you want to back up specific tables instead of the entire database, specify the table names as shown below:

mysqldump -u username -p database_name table1 table2 > output_file.sql

For example, to back up only the users and orders tables:

mysqldump -u root -p shop_db users orders > users_orders.sql

Backing Up Multiple Databases

Using the -B option allows you to back up multiple databases at once:

mysqldump -u username -p -B database1 database2 > multi_backup.sql

This method includes CREATE DATABASE statements, making it convenient for restoration.

Backing Up All Databases at Once

If you need a full system backup, use -A (or --all-databases):

mysqldump -u username -p -A > all_databases.sql

This command dumps all databases on the MySQL server, including system databases such as mysql and information_schema, making it suitable for environment migrations.

How to Restore a Backup

An SQL file created with mysqldump can be restored using the following command:

mysql -u username -p database_name < output_file.sql

This allows you to restore backup data to a new environment or recover from corruption.

3. Details of the –single-transaction Option

The Key to Maintaining Consistency During Backups

By default, the mysqldump command dumps tables one by one in sequence. As a result, if another user modifies data during the backup process, an “in-between” state may be saved, which can break data consistency when you restore.

The option that solves this problem is --single-transaction.

How –single-transaction Works

When you use this option, mysqldump executes a BEGIN statement at the start of the dump process to start a transaction. This creates a snapshot of the database at that point in time. Even if other transactions make changes during the dump, the backup can complete without being affected.

In other words, it lets you back up the entire database as it existed at the exact moment the dump started—so consistency is preserved.

Works Only with InnoDB

A critical point to understand is that --single-transaction is effective only for tables using the InnoDB storage engine. InnoDB supports transactions, which makes it possible to create and maintain snapshots.

On the other hand, if you use non-transactional storage engines such as MyISAM or MEMORY, --single-transaction will not provide the intended consistency. In those cases, you may need lock-based alternatives such as --lock-tables or --lock-all-tables.

Difference from Table Locks

By default, mysqldump locks tables to maintain consistency (because --lock-tables is automatically enabled). However, this approach has a major drawback: other users cannot update data—meaning the service may effectively be disrupted.

With --single-transaction, you can back up without locks, which means you can perform backups without stopping the service. This is extremely valuable in production environments.

Illustration (Text Explanation)

[Regular mysqldump]
Time passes → [Start dumping users table] → [Data changes mid-way] → [Start dumping orders table] → Inconsistency occurs

[Using --single-transaction]
Time passes → [Create snapshot with BEGIN] → [Dump users and orders from the same consistent point in time] → Safe backup completed

Important: Not Effective Against DDL Operations

--single-transaction is strong against data changes (INSERT, UPDATE, DELETE), but it is not effective against schema changes (DDL) such as CREATE, DROP, or ALTER. If DDL is executed during a backup, errors or inconsistencies may occur.

For this reason, it is ideal to schedule backups during a maintenance window or at a time when DDL changes can be avoided.

Summary

--single-transaction is an extremely effective way to obtain consistent backups without stopping service in MySQL environments that use InnoDB. By understanding how it works and using it correctly, you can achieve safe and efficient data protection.

4. How to Use the –single-transaction Option

Basic Command Example

Let’s start with the simplest way to use --single-transaction:

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

This command saves the state of the database at the moment the transaction begins (for databases using InnoDB). A major advantage is that it does not interfere with other processing during the backup, so you can run it without stopping the service.

Backing Up Multiple Tables

You can also apply --single-transaction to specific tables only:

mysqldump --single-transaction -u root -p shop_db users orders > users_orders.sql

Even when specifying individual tables, mysqldump creates a consistent snapshot and exports data from the same point in time.

Backing Up Multiple Databases

To back up multiple databases, combine it with -B (or --databases):

mysqldump --single-transaction -u root -p -B db1 db2 > multi_db_backup.sql

This format includes CREATE DATABASE statements for each database, improving convenience during restores.

Backing Up All Databases

If you need a full server backup, use it with -A (or --all-databases):

mysqldump --single-transaction -u root -p -A > full_backup.sql

This dumps all databases on the MySQL server (including mysql, information_schema, performance_schema, etc.), making it useful for server migrations and full restores.

Key Checks Before Running

  • Ensure the storage engine is InnoDB --single-transaction is effective only for InnoDB. With non-transactional engines like MyISAM, it will not behave as expected.
  • Do not combine it with --lock-tables Because --single-transaction and --lock-tables are conflicting behaviors, combining them can break consistency guarantees. For safety, it is a good idea to explicitly add --skip-lock-tables.

Common Recommended Example (Best Practice)

mysqldump --single-transaction --quick --skip-lock-tables -u root -p production_db > backup.sql

This setup has the following characteristics:

  • --quick: Reduces memory usage by outputting rows as they are read, rather than loading everything into memory at once
  • --skip-lock-tables: Explicitly avoids automatic locks to ensure safe behavior

Automation Example Using a Shell Script

In real operations, it’s common to script regular backups and run them automatically with cron, etc.

#!/bin/bash
DATE=$(date +%F)
mysqldump --single-transaction --quick --skip-lock-tables -u root -pYourPassword production_db > /backups/production_$DATE.sql

Note: It is recommended to manage passwords using environment variables or configuration files.

5. Important Considerations When Using –single-transaction

No Effect on Non-Transactional Engines (e.g., MyISAM)

This option is effective only for transactional storage engines (primarily InnoDB). Engines such as MyISAM and MEMORY do not support transactions, so specifying --single-transaction does not guarantee consistency.

Example:

  • users table uses InnoDB
  • logs table uses MyISAM

In such a mixed environment, the users table remains consistent, but the logs table may be affected by concurrent operations during the backup.

Countermeasures:

  • Standardize on InnoDB whenever possible.
  • If MyISAM or other engines are mixed in, consider using --lock-all-tables.

Not Effective Against DDL Operations (Schema Changes)

While --single-transaction works well against data operations (SELECT, INSERT, UPDATE, DELETE), it does not protect against DDL operations (CREATE, DROP, ALTER, etc.).

If table definitions change during a dump, risks include:

  • A table is dropped mid-dump → error occurs
  • A table definition changes during dump → schema inconsistency

Countermeasures:

  • Establish a rule to avoid DDL during backups.
  • Perform backups during a maintenance window whenever possible.

Do Not Combine with --lock-tables

By default, mysqldump enables --lock-tables, but this behavior conflicts with --single-transaction. Table locks are executed before the transaction begins, which can break consistency guarantees.

Therefore, when using --single-transaction, it is recommended to explicitly add --skip-lock-tables.

mysqldump --single-transaction --quick --skip-lock-tables -u root -p dbname > backup.sql

Consistency Is Guaranteed Only at the Start Point

--single-transaction captures a snapshot of the database at the moment the transaction begins. Any changes made afterward are naturally not included in the dump.

This avoids lock contention during the dump, but it is important to understand that it represents a snapshot at a specific point in time.

Use –quick for Large Datasets

When backing up large datasets, mysqldump may attempt to load entire tables into memory by default, potentially causing memory exhaustion or swapping.

In such cases, combine it with --quick, which reads and outputs rows one by one, significantly reducing memory usage.

mysqldump --single-transaction --quick --skip-lock-tables -u root -p dbname > backup.sql

Summary

--single-transaction is a powerful option for achieving consistent backups without stopping service. However, proper use requires understanding its limitations. In production environments, carefully consider storage engines, DDL activity, and timing when designing your backup strategy.

6. Combining –single-transaction with Other Options

–quick: The Best Partner for Reducing Memory Usage

mysqldump --single-transaction --quick -u root -p dbname > backup.sql

When you add --quick, mysqldump does not load all data into memory at once. Instead, it reads and outputs rows one at a time. This is especially effective for large tables and significantly reduces memory consumption.

Benefits:

  • Lower memory usage during backup
  • Prevents swapping and performance degradation
  • Improves stability in large data environments

Recommendation: If you use --single-transaction, it is almost always best practice to use it together with --quick.

–skip-lock-tables: Explicitly Avoid Automatic Locks

mysqldump attempts to enable --lock-tables by default, but this conflicts with --single-transaction. To avoid conflicts, explicitly specify --skip-lock-tables.

mysqldump --single-transaction --quick --skip-lock-tables -u root -p dbname > backup.sql

Benefits:

  • Clarifies command intent
  • Prevents errors or warnings caused by option conflicts

–master-data: Ideal for Replication Setups

In MySQL replication environments, --master-data is commonly used to ensure accurate synchronization on the replica side.

mysqldump --single-transaction --quick --master-data=2 -u root -p dbname > repl_backup.sql

When specifying --master-data=2, the current binary log file name and position are recorded in the dump file as commented lines. This allows you to synchronize replicas using that information.

Important:

  • --master-data should also be used primarily with InnoDB.
  • It is sometimes combined with --flush-logs to rotate binary logs.

–set-gtid-purged=OFF: When You Want to Disable GTID

In environments using GTID (Global Transaction ID), mysqldump may automatically include GTID information. In some cases, you may want to disable this behavior.

mysqldump --single-transaction --quick --set-gtid-purged=OFF -u root -p dbname > no_gtid.sql

Use Cases:

  • Temporary backups outside replication setups
  • Transferring data to a different environment

Comprehensive Example (Combined Options)

mysqldump   --single-transaction   --quick   --skip-lock-tables   --master-data=2   --set-gtid-purged=OFF   -u root -p production_db > production_backup.sql

By combining multiple options, you can build a practical backup script that addresses consistency, memory efficiency, replication compatibility, and GTID management.

Summary

While --single-transaction is powerful on its own, combining it with other options enables an optimal backup strategy tailored to your environment and goals. In particular, pairing it with --quick and --skip-lock-tables is nearly essential, and in replication environments, you should consider using --master-data as well.

To fully leverage mysqldump, selecting options based on your purpose is key.

7. Frequently Asked Questions (FAQ)

Here we summarize common practical questions about mysqldump --single-transaction along with their answers. Use this section as a reference for preventing operational issues and designing a reliable backup strategy.

Q1. In what situations is the --single-transaction option appropriate?

A1.
It is ideal when using the InnoDB storage engine and when you want to obtain a consistent backup without stopping the service. It is particularly valuable in production environments such as e-commerce sites or reservation systems where users are constantly accessing the system.

Q2. Can I use --single-transaction if MyISAM tables are included?

A2.
Yes, you can use it, but data consistency for MyISAM tables is not guaranteed. Since MyISAM does not support transactions, updates during backup may lead to inconsistencies. If MyISAM tables are included, consider using --lock-all-tables instead.

Q3. What happens if I use --single-transaction and --lock-tables together?

A3.
These options conflict with each other, and mysqldump will automatically disable one of them. However, to avoid unintended behavior or warnings, it is safer to explicitly specify --skip-lock-tables.

Q4. What if DDL operations such as CREATE TABLE or ALTER TABLE occur during the dump?

A4.
--single-transaction does not protect against DDL operations. If table definitions change during the dump, there is a risk of backup failure or inconsistent results. Ideally, schedule backups during maintenance windows or at times when DDL operations can be avoided.

Q5. Are there recommended options to use together with --single-transaction?

A5.
Yes, combining the following options improves safety and efficiency:

  • --quick: Reduces memory usage and enables stable dumps
  • --skip-lock-tables: Explicitly avoids table lock conflicts
  • --master-data=2: Supports replication-compatible backups
  • --set-gtid-purged=OFF: Provides flexibility in non-GTID environments

Q6. How can I shorten backup time?

A6.
The following measures are effective:

  • Use the --quick option to reduce memory load and improve speed
  • Back up only specific tables (partial backups)
  • Archive or delete unnecessary data in advance to reduce dataset size
  • Output backup files to SSD or high-speed storage

Q7. How do I restore a backup created with --single-transaction?

A7.
You can restore it just like a normal mysqldump file using the following command:

mysql -u username -p database_name < backup.sql

If the backup includes binary log or GTID information, additional configuration may be required before restoring (for example, using the CHANGE MASTER TO command).

8. Conclusion

mysqldump --single-transaction is a powerful method for obtaining consistent backups without stopping service in MySQL and MariaDB environments. In this article, we covered its mechanism, usage, important considerations, option combinations, and frequently asked questions in detail.

Key Takeaways

  • --single-transaction leverages InnoDB’s transaction functionality to provide snapshot-based, consistent backups.
  • It allows you to avoid table locks and safely dump data even in production environments.
  • However, it does not support non-transactional engines like MyISAM or DDL operations, so proper understanding of your environment is essential.
  • Combining it with options such as --quick, --skip-lock-tables, and --master-data enhances both quality and efficiency.
  • The FAQ section addresses practical concerns commonly encountered in real-world operations.

Build a Safe and Efficient Backup Strategy

In business and service operations, data loss directly impacts credibility. By properly using mysqldump and --single-transaction, you can establish a backup strategy that balances reliability and practicality.

The key is to move beyond simply “having backups” and aim for consistent, reliable backups you can trust during failures. Apply the knowledge from this article to strengthen your daily operations.