目次
- 1 1. What is a MySQL transaction?
- 2 2. Basic Transaction Operations in MySQL
- 3 3. Isolation Levels and Their Impact
- 4 4. Transaction Practical Scenarios
- 5 5. Pitfalls to Watch Out For and Performance Strategies
- 6 6. Tips Not Covered in Other Articles
- 7 7. Frequently Asked Questions (FAQ)
- 8 8. Summary
1. What is a MySQL transaction?
Definition and Necessity of Transactions
A transaction refers to a processing unit that treats multiple database operations as a single unit. For example, consider a bank transfer. Withdrawing money from A’s account and depositing it into B’s account are performed with two SQL queries. If only one side of the operation were executed, the monetary consistency would be broken. Thus, either successfully complete the entire series of operations or roll back everything is required. This is where transactions come in. Transactions play a crucial role in maintaining data integrity.What are the “ACID properties” of a transaction?
Transactions must satisfy four characteristics known as the “ACID properties” to ensure reliable processing.- Atomicity (atomicity) All operations within a transaction are either all successful or all failed. If an error occurs partway through, all operations are canceled.
- Consistency (consistency) It guarantees that the database integrity is always maintained before and after the transaction. For example, it ensures that inventory counts never become negative.
- Isolation (isolation) Even when multiple transactions run concurrently, they must be processed so that they do not interfere with each other. This allows stable processing without being affected by other transactions.
- Durability (durability) Once a transaction is deemed “successful” and committed, the changes are guaranteed to be permanently stored in the database. They will not be lost even in the event of a power failure.
Benefits of Using Transactions in MySQL
In MySQL, transactions are supported by using the InnoDB storage engine. Older storage engines such as MyISAM do not support transactions, so caution is required. Using transactions in MySQL provides the following benefits:- Ability to revert data to its previous state on error (ROLLBACK)
- Manage multi-step operations as a single logical unit
- Maintain consistency even during system failures
2. Basic Transaction Operations in MySQL
Starting, Committing, and Rolling Back Transactions
The basic operations for using transactions in MySQL are the following three commands.START TRANSACTION
orBEGIN
: Start a transactionCOMMIT
: Commit and save changesROLLBACK
: Roll back changes to the original state
Example of a basic flow:
START TRANSACTION;
UPDATE accounts SET balance = balance - 10000 WHERE id = 1;
UPDATE accounts SET balance = balance + 10000 WHERE id = 2;
COMMIT;
In this way, starting with START TRANSACTION
and finalizing with COMMIT
causes the two update operations to be applied together as a single transaction. If an error occurs partway through, you can use ROLLBACK
to undo all changes.ROLLBACK;
How to Configure Autocommit and Differences in Behavior
In MySQL, autocommit mode (autocommit) is enabled by default. In this state, each individual SQL statement is committed immediately as it is executed.Check the current setting:
SELECT @@autocommit;
How to disable autocommit:
SET autocommit = 0;
With this setting, changes are held pending until you explicitly end the transaction. This allows you to manage multiple operations together.Example: Safely Executing Multiple UPDATEs
The following example groups the stock reduction and the insertion of a sales record into a transaction.START TRANSACTION;
UPDATE products SET stock = stock - 1 WHERE id = 10 AND stock > 0;
INSERT INTO sales (product_id, quantity, sale_date) VALUES (10, 1, NOW());
COMMIT;
The key is to include the condition stock
so that the stock count does not go negative if the inventory is zero. As needed, you can check the number of rows affected and combine logic to ROLLBACK
if no rows were updated.3. Isolation Levels and Their Impact
What is Isolation Level? Comparison of 4 Types
In RDBMSs, including MySQL, it is not uncommon for multiple transactions to be executed simultaneously. In such cases, the mechanism that controls transactions so they do not interfere with each other is the “Isolation Level”. There are four levels of isolation. Higher levels more strongly suppress interference between transactions, but they can affect performance.Isolation Level | Description | MySQL Default |
---|---|---|
READ UNCOMMITTED | Can read uncommitted data from other transactions | × |
READ COMMITTED | Can read only committed data | × |
REPEATABLE READ | Always reads the same data within the same transaction | ◎ (default) |
SERIALIZABLE | Fully serialized processing. Most strict but slower | × |
Phenomena That May Occur at Each Isolation Level
Differences in isolation levels can lead to three consistency-related issues. Understanding each phenomenon and which isolation level can prevent it is important.- Dirty Read
- Reading data that another transaction has not yet committed.
- Preventable level: READ COMMITTED or higher
- Non-Repeatable Read
- The data changes due to another transaction when the same query is executed multiple times.
- Preventable level: REPEATABLE READ or higher
- Phantom Read
- When new rows are added or removed by another transaction, causing the result set of a query with the same condition to change.
- Preventable level: SERIALIZABLE only
How to Set Isolation Levels and Example Execution
In MySQL, you can set the isolation level per session or globally.Session-level Setting (Common Usage)
SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;
Check the Current Isolation Level
SELECT @@transaction_isolation;
Example: Difference Between REPEATABLE READ and READ COMMITTED
-- Session A
START TRANSACTION;
SELECT * FROM products WHERE id = 10;
-- Session B
UPDATE products SET stock = stock - 1 WHERE id = 10;
COMMIT;
-- Session A
SELECT * FROM products WHERE id = 10; -- No change under REPEATABLE READ
Thus, setting the isolation level appropriately is extremely important for maintaining data integrity. However, strict isolation levels can negatively impact performance, so adjustments based on the use case are required.
4. Transaction Practical Scenarios
Examples of Use in Inventory Management and E‑commerce Sites
In e‑commerce sites, the product inventory must be updated during order processing. At that time, if multiple users attempt to purchase the same product simultaneously, there is a risk of inaccurate inventory counts. By using transactions here, you can ensure data consistency while handling concurrent operations.Example: Decreasing inventory and recording order history in a single transaction
START TRANSACTION;
UPDATE products SET stock = stock - 1 WHERE id = 101 AND stock > 0;
INSERT INTO orders (product_id, quantity, order_date) VALUES (101, 1, NOW());
COMMIT;
If the inventory is zero, the key is to specify the condition stock > 0
so that the stock count does not go negative. As needed, you can check the number of rows affected and combine logic to ROLLBACK
if no rows were updated.Designing Transactions for Bank Transfer Processing
Inter‑account transfers in banks are a classic use case for transactions.- Debit account A
- Credit the same amount to account B
Example: Transfer Processing
START TRANSACTION;
UPDATE accounts SET balance = balance - 10000 WHERE id = 1;
UPDATE accounts SET balance = balance + 10000 WHERE id = 2;
COMMIT;
In production, you include business logic such as checks to prevent account balances from going negative and limits on transfer amounts, and perform additional validation on the application side.Code Examples of Using Transactions with Laravel and PHP
In recent years, opportunities to handle transactions through frameworks have increased. Here we introduce how to use transactions in the popular PHP framework Laravel.Transaction Handling in Laravel
DB::transaction(function () {
DB::table('accounts')->where('id', 1)->decrement('balance', 10000);
DB::table('accounts')->where('id', 2)->increment('balance', 10000);
});
By using the DB::transaction()
function, the framework automatically manages BEGIN
, COMMIT
, and ROLLBACK
internally, enabling safe and readable code.Example: Manual Transaction with try‑catch
DB::beginTransaction();
try {
// processing logic
DB::commit();
} catch (Exception $e) {
DB::rollBack();
// log output, notifications, etc.
}
In this way, by leveraging framework and language features, you can manage transactions without writing raw SQL.5. Pitfalls to Watch Out For and Performance Strategies
Transactions are a powerful mechanism, but using them incorrectly can cause performance degradation and unexpected problems. This section outlines the points to watch when using transactions in MySQL and the corresponding countermeasures.Operations That Cannot Be Rolled Back (DDL)
The basic advantage of a transaction is that you can revert operations with ROLLBACK, but not every SQL statement is rollback‑able. In particular, you need to be careful with operations that use Data Definition Language (DDL). For example, the following actions cannot be rolled back.CREATE TABLE
ALTER TABLE
DROP TABLE
Causes of Deadlocks and How to Avoid Them
Heavy use of transactions can lead to multiple transactions waiting on each other to release resources, potentially causing a deadlock where processing never progresses.Deadlock Example (Simplified)
- Transaction A locks row 1 and waits for the lock on row 2
- Transaction B locks row 2 and waits for the lock on row 1
Avoidance Strategies
- Standardize lock ordering When updating rows in the same table, design the code to always access them in the same order.
- Keep transaction duration short Exclude unnecessary work and issue
COMMIT
orROLLBACK
as soon as possible. - Limit the number of rows accessed Use precise WHERE clauses to narrow the target and avoid locking the entire table.
Checklist When Transactions Feel Slow
There are many factors that can slow down transaction processing. Checking the following items can help identify bottlenecks.- Are indexes set appropriately? Ensure columns used in WHERE clauses or JOIN conditions have indexes.
- Is the isolation level too high? Verify you aren’t using an unnecessarily high isolation level (e.g., SERIALIZABLE).
- Is autocommit still enabled during processing? Check that you are managing transactions explicitly.
- Are transactions being held for too long? A long interval between start and COMMIT can cause lock contention.
- Are InnoDB buffer pool and log sizes appropriate? Consider tuning the server settings relative to your data volume.
6. Tips Not Covered in Other Articles
The basics and best practices of MySQL transactions are covered on many technical sites, but articles that also cover the fine‑grained techniques useful in real work and troubleshooting are few. This section introduces practical tips to deepen your understanding of MySQL transactions and apply them in practice.How to Check Running Transactions
When multiple transactions are running concurrently, you may need to understand the situation. In MySQL, you can use the following command to check InnoDB lock status and transaction status.SHOW ENGINE INNODB STATUSG
This command outputs the internal state of the InnoDB storage engine, providing information such as:- List of running transactions
- Transactions waiting for locks
- Deadlock history
How to Analyze Behavior from SQL and Slow Query Logs
Identifying transaction problems also requires checking logs. MySQL provides the following logging features.- General log: records all SQL statements
- Slow query log: records only queries that took a long time to execute
Example of Enabling Slow Query Log (my.cnf)
slow_query_log = 1
slow_query_log_file = /var/log/mysql/slow.log
long_query_time = 1
With this configuration, only queries that took longer than one second are logged. If a transaction includes time‑consuming queries, this helps identify the cause of performance degradation.Experimenting with Transaction Behavior Across Multiple Sessions
Understanding transaction mechanics in theory is not enough; hands‑on experimentation is also important. By opening two terminals and processing the same row from different sessions as shown below, you can experience differences in isolation levels and lock behavior.Experiment Example: Verifying Behavior with REPEATABLE READ
- Session A
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
START TRANSACTION;
SELECT * FROM products WHERE id = 1;
-- Keep result
- Session B
UPDATE products SET name = 'Updated product name' WHERE id = 1;
COMMIT;
- Session A
SELECT * FROM products WHERE id = 1;
-- Change is not visible yet (because of REPEATABLE READ)
COMMIT;
Through such experiments, you can prevent mismatches between logic and behavior and achieve more accurate implementations.7. Frequently Asked Questions (FAQ)
Regarding MySQL transactions, many questions are raised that go beyond basic usage and directly relate to doubts and issues that frequently arise during operation. In this section, we have compiled the most common questions and their answers from real development environments in a Q&A format.Q1. Are there cases where transactions cannot be used in MySQL?
Yes, there are. If the MySQL storage engine is not InnoDB, transaction support is unavailable. In particular, older systems may be using MyISAM, and in that case transactions will not work, so caution is required. How to check:SHOW TABLE STATUS WHERE Name = 'table_name';
Make sure that the Engine
is InnoDB
.Q2. Is it true that using transactions slows down processing?
It is not necessarily the case, but if the transaction design is not appropriate, it can affect performance. The following reasons are possible:- Holding a transaction open for a long time
- Using an unnecessarily high isolation level
- Insufficient index design leading to a wide lock scope
Q3. Does simply disabling autocommit create a transaction?
ExecutingSET autocommit = 0;
causes all subsequent queries to remain pending unless an explicit COMMIT
or ROLLBACK
is issued. This can unintentionally include multiple operations in a transaction, which may actually cause problems.
Therefore, when disabling autocommit, it is important to be conscious of explicit transaction start and end management.Q4. What should you do when an error occurs during a transaction?
If an error occurs during a transaction, the standard practice is to executeROLLBACK
to revert the state. It is common to handle transaction control together with exception handling on the application side.Example (PHP + PDO)
try {
$pdo->beginTransaction();
// SQL operation
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
// Record error log, etc.
}
By implementing proper error handling, you can prevent incomplete data writes and improve the overall reliability of the system.8. Summary
In this article, we covered the topic of “MySQL transactions,” ranging from fundamentals to practical use, as well as troubleshooting and tips. Finally, let’s review what we’ve covered and organize the key points of transactions in MySQL.Transactions are the key to increasing reliability
A transaction is the core feature that groups multiple SQL operations into a single unit of work to preserve data integrity and reliability. Proper transaction design is essential especially in finance, inventory management, reservation systems, and similar domains.Correct control and understanding are crucial
- Master the basic operations from
START TRANSACTION
toCOMMIT
/ROLLBACK
- Understand the difference between autocommit and explicit transaction management
- Adjust isolation levels to suit your goals, balancing performance and consistency