MySQL Transactions Explained: ACID, Isolation Levels, COMMIT & ROLLBACK Guide

目次

1. What Is a MySQL Transaction?

Definition and Importance of Transactions

A transaction refers to a unit of work that treats multiple database operations as a single logical group. For example, consider a bank transfer. Withdrawing money from Person A’s account and depositing it into Person B’s account requires two SQL queries. If only one of these operations executes successfully, financial consistency would be broken.

This is why we need a mechanism that ensures either all operations succeed or all are rolled back. That mechanism is called a transaction. Transactions play a crucial role in maintaining data integrity.

What Are the ACID Properties?

To ensure reliable processing, transactions must satisfy four properties known as ACID.

  • Atomicity
    All operations within a transaction must either succeed entirely or fail entirely. If an error occurs midway, all changes are canceled.
  • Consistency
    Guarantees that database integrity is preserved before and after the transaction. For example, inventory quantities should never become negative.
  • Isolation
    Even when multiple transactions run simultaneously, they must be processed without interfering with one another. This ensures stable execution unaffected by other transactions.
  • Durability
    Once a transaction is committed successfully, its changes are permanently saved to the database. Even power failures will not cause data loss.

By adhering to ACID properties, applications can achieve highly reliable data operations.

Benefits of Using Transactions in MySQL

In MySQL, transactions are supported when using the InnoDB storage engine. Older engines such as MyISAM do not support transactions, so be cautious.

Using transactions in MySQL provides the following benefits:

  • Restore data state when errors occur (ROLLBACK)
  • Manage multi-step operations as a single logical unit
  • Maintain consistency even during system failures

Especially in systems with complex business logic—such as eCommerce platforms, financial systems, and inventory management—transaction support directly impacts overall reliability.

2. Basic Transaction Operations in MySQL

Starting, Committing, and Rolling Back Transactions

The three fundamental commands used for transactions in MySQL are:

  • START TRANSACTION or BEGIN: Start a transaction
  • COMMIT: Confirm and save changes
  • ROLLBACK: Cancel changes and restore the previous state

Basic Workflow Example:

START TRANSACTION;

UPDATE accounts SET balance = balance - 10000 WHERE id = 1;
UPDATE accounts SET balance = balance + 10000 WHERE id = 2;

COMMIT;

By starting with START TRANSACTION and finalizing with COMMIT, both update operations are applied together as a single logical process. If an error occurs midway, you can cancel all changes using ROLLBACK.

ROLLBACK;

Autocommit Settings and Behavioral Differences

By default, MySQL enables autocommit mode. In this mode, each SQL statement is automatically committed immediately after execution.

Check Current Setting:

SELECT @@autocommit;

Disable Autocommit:

SET autocommit = 0;

When autocommit is disabled, changes remain pending until you explicitly end the transaction. This allows multiple operations to be managed together.

Example: Safely Executing Multiple UPDATE Statements

The following example groups inventory reduction and sales record insertion within a single 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 point is using the condition stock > 0 to prevent inventory from becoming negative. If necessary, you can check the affected row count and execute ROLLBACK if no rows were updated.

3. Isolation Levels and Their Impact

What Is an Isolation Level? Comparing the Four Types

In RDBMSs (Relational Database Management Systems), including MySQL, it’s common for multiple transactions to run at the same time. The mechanism that controls transactions so they don’t interfere with one another is called the Isolation Level.

There are four isolation levels. Higher levels reduce interference between transactions more strictly, but they can also impact performance.

Isolation LevelDescriptionMySQL Default
READ UNCOMMITTEDCan read uncommitted data from other transactions×
READ COMMITTEDCan read only committed data×
REPEATABLE READAlways reads the same data within the same transaction◎ (Default)
SERIALIZABLEFully serialized execution; most strict but slowest×

Phenomena That May Occur at Each Isolation Level

Depending on the isolation level, three consistency-related issues may occur. It’s important to understand what they are and which isolation levels prevent them.

  1. Dirty Read
  • Reading data that another transaction has not yet committed.
  • Prevented by: READ COMMITTED or higher
  1. Non-Repeatable Read
  • Running the same query multiple times returns different results because another transaction changed the data.
  • Prevented by: REPEATABLE READ or higher
  1. Phantom Read
  • Rows are added or removed by another transaction, causing the same search condition to return a different result set.
  • Prevented by: SERIALIZABLE only

How to Set Isolation Levels (with Examples)

In MySQL, isolation levels can be set per session or globally.

Session-Level Setting (Common Approach)

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

As shown above, setting the appropriate isolation level is critical for maintaining data integrity. However, stricter levels may negatively affect performance, so you should tune them based on your use case.

4. Practical Transaction Scenarios

Examples in Inventory Management and eCommerce

In eCommerce systems, you must update product inventory when processing orders. If multiple users attempt to purchase the same product at the same time, inventory can become inaccurate. By using transactions, you can handle concurrent operations while preserving data consistency.

Example: Decrease Inventory and Insert Order History in One 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;

The key point is using stock > 0 to prevent inventory from becoming negative. If needed, you can also check the number of updated rows and run ROLLBACK when nothing was updated.

Designing Transactions for Bank Transfers

A bank transfer between accounts is a classic use case for transactions.

  • Decrease the balance from Account A
  • Increase the balance by the same amount in Account B

If either operation fails, you must roll back the entire process (ROLLBACK).

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 real-world production systems, the application typically adds extra validation—such as preventing negative balances or enforcing transfer limits—as part of business logic.

Transaction Examples in Laravel and PHP

In recent years, it’s increasingly common to manage transactions through frameworks. Here, we’ll look at how to use transactions in the popular PHP framework Laravel.

Transactions 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() method, Laravel automatically manages BEGIN, COMMIT, and ROLLBACK internally, resulting in safe and readable code.

Example: Manual Transactions with try-catch

DB::beginTransaction();

try {
    // Processing logic
    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
    // Logging or notification, etc.
}

By leveraging framework and language features, you can manage transactions without writing raw SQL directly.

5. Common Pitfalls and Performance Optimization

Transactions are powerful, but incorrect usage can cause performance degradation and unexpected issues. In this section, we explain important considerations and countermeasures when using transactions in MySQL.

Operations That Cannot Be Rolled Back (DDL)

One of the key advantages of transactions is the ability to restore changes using ROLLBACK. However, not all SQL statements can be rolled back.

Be especially careful with operations using Data Definition Language (DDL). The following statements cannot be rolled back:

  • CREATE TABLE
  • ALTER TABLE
  • DROP TABLE

These statements are committed immediately upon execution and are not affected by transaction control. Therefore, DDL operations should always be executed outside of transactions.

Deadlocks: Causes and Prevention

When transactions are heavily used, multiple transactions may end up waiting indefinitely for each other’s resources. This situation is known as a deadlock.

Example of a Deadlock (Simplified)

  • Transaction A locks row 1 and waits for row 2
  • Transaction B locks row 2 and waits for row 1

When this occurs, MySQL automatically forces one of the transactions to roll back.

Prevention Strategies

  • Standardize lock order
    When updating rows in the same table, always access them in a consistent order.
  • Keep transactions short
    Avoid unnecessary processing inside transactions and execute COMMIT or ROLLBACK as quickly as possible.
  • Limit the number of affected rows
    Use precise WHERE clauses to avoid locking entire tables.

Checklist When Transactions Feel Slow

There are many possible causes of slow transaction performance. Reviewing the following points can help identify bottlenecks:

  • Are indexes properly configured?
    Columns used in WHERE clauses or JOIN conditions should have indexes.
  • Is the isolation level too high?
    Confirm you are not unnecessarily using strict levels like SERIALIZABLE.
  • Is autocommit left enabled unintentionally?
    Ensure you are managing transactions explicitly where needed.
  • Are transactions being held open too long?
    Long gaps between START TRANSACTION and COMMIT can cause lock contention.
  • Are InnoDB buffer pool and log sizes appropriate?
    Verify that server settings match your data volume and consider tuning if necessary.

6. Advanced Tips You Rarely See Elsewhere

While many technical websites explain MySQL transaction basics, fewer articles cover practical techniques useful in production and troubleshooting. This section introduces practical tips to deepen your understanding.

How to Check Running Transactions

When multiple transactions are running concurrently, you may need to inspect their status. In MySQL, you can check InnoDB lock status and transaction information using the following command:

SHOW ENGINE INNODB STATUS\G

This command outputs internal InnoDB state, including:

  • List of running transactions
  • Transactions waiting for locks
  • Deadlock history

When complex issues occur, this information is often the first step in debugging.

Analyzing Behavior with SQL Logs and Slow Query Logs

To diagnose transaction issues, log analysis is essential. MySQL provides several logging features:

  • General Log: Records all SQL statements
  • Slow Query Log: Records only queries that exceed a specified execution time

Example: Enabling the 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, queries taking longer than one second are recorded. If a transaction contains slow queries, this log helps identify the cause of performance degradation.

Experimenting with Multiple Sessions to Understand Behavior

Understanding transactions conceptually is important, but hands-on experimentation is equally valuable. By opening two terminals and executing queries in separate sessions, you can observe isolation level differences and lock behavior.

Experiment Example: Behavior Under REPEATABLE READ

  • Session A
SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;
START TRANSACTION;
SELECT * FROM products WHERE id = 1;
-- Hold the result
  • Session B
UPDATE products SET name = 'Updated Product Name' WHERE id = 1;
COMMIT;
  • Session A
SELECT * FROM products WHERE id = 1;
-- The change is still not visible (due to REPEATABLE READ)
COMMIT;

Through experiments like this, you can eliminate mismatches between logic and actual behavior and implement more accurate systems.

7. Frequently Asked Questions (FAQ)

In addition to basic usage, many practical questions arise when working with MySQL transactions in real-world environments. In this section, we summarize common questions and answers in a Q&A format.

Q1. Are there situations where transactions cannot be used in MySQL?

Yes. If the MySQL storage engine is not InnoDB, transaction functionality is not supported. In older systems, MyISAM may still be used, and in such cases, transactions will not work.

How to check:

SHOW TABLE STATUS WHERE Name = 'table_name';

Make sure that the Engine column shows InnoDB.

Q2. Does using transactions always make processing slower?

Not necessarily. However, poor transaction design can negatively impact performance.

Possible causes include:

  • Keeping transactions open for too long
  • Using unnecessarily strict isolation levels
  • Insufficient indexing that broadens the locking scope

In such cases, lock contention and buffer pool load may reduce performance.

Q3. Does disabling autocommit automatically make everything a transaction?

When you execute SET autocommit = 0;, all subsequent queries remain pending until an explicit COMMIT or ROLLBACK is executed. This can unintentionally include multiple operations in the same transaction and may cause unexpected issues.

Therefore, if you disable autocommit, it is important to clearly manage the start and end of transactions.

Q4. What should I do if an error occurs during a transaction?

If an error occurs during a transaction, you should generally execute ROLLBACK to restore the previous state. On the application side, transaction control is typically combined with exception handling.

Example (PHP + PDO)

try {
    $pdo->beginTransaction();

    // SQL processing
    $pdo->commit();
} catch (Exception $e) {
    $pdo->rollBack();
    // Record error logs, etc.
}

Proper error handling helps prevent incomplete data writes and improve overall system reliability.

8. Summary

In this article, we explored the topic of “MySQL Transactions” from fundamentals to practical applications, including troubleshooting strategies and advanced tips. Let’s recap the key points.

Transactions Are the Key to Reliability

A transaction is a core feature that groups multiple SQL operations into a single unit to preserve data integrity and reliability. In systems such as financial platforms, inventory management, and reservation systems, proper transaction design is essential.

Correct Control and Understanding Are Crucial

  • Master the basic flow from START TRANSACTION to COMMIT and ROLLBACK
  • Understand the difference between autocommit mode and explicit transaction management
  • Adjust isolation levels appropriately to balance performance and consistency

Practical Scenarios and Tips Make You Stronger in Production

In real development and operations environments, it’s not enough to know the syntax. You must also understand how to inspect running transactions and troubleshoot issues using logs and monitoring tools.

MySQL transactions are often researched only when problems arise. By learning them systematically in advance, you gain a powerful skill that directly improves system reliability and performance.

We hope this guide deepens your understanding of transactions and gives you confidence in your daily development and operations work.

If you have questions or topics you’d like covered in more detail, feel free to leave a comment. We will continue providing practical and actionable technical insights.