Table of Contents
4. Actual situation demonstration" >4. Actual situation demonstration
Home Database Mysql Tutorial What are the mysql transaction isolation levels?

What are the mysql transaction isolation levels?

Jan 04, 2023 pm 04:37 PM
mysql transaction isolation

There are four transaction isolation levels: 1. Read Uncommitted (read uncommitted), which allows reading of uncommitted data changes, which may cause dirty reads, non-repeatable reads, and phantom reads. 2. Read Committed (Read Committed) allows reading data that has been submitted by concurrent transactions, which can avoid dirty reads, but may cause non-repeatable and phantom reads. 3. Repeatable Read (repeatable read), the results of multiple reads of the same field are consistent. 4. Serializable (serializable).

What are the mysql transaction isolation levels?

The operating environment of this tutorial: windows7 system, mysql8 version, Dell G3 computer.

1. What is a transaction?

A transaction is a logical set of operations, either all of them are executed or none of them are executed.

The most classic and often mentioned chestnut in affairs is bank transfer. For example, if Xiao Ming wants to transfer 1,000 yuan to Xiao Hong, this transfer will involve two key operations: reducing Xiao Ming's balance by 1,000 yuan and reducing Xiao Hong's balance by 1,000 yuan. If an error suddenly occurs between these two operations, causing Xiao Ming's balance to decrease but Xiao Hong's balance not to increase, this situation is definitely not allowed. The transaction is to ensure that these two key operations either succeed or neither succeeds.

2. Transaction characteristics (ACID)

  • **Atomicity:* *The smallest execution unit of a transaction, no division is allowed. The atomicity of transactions ensures that actions are either all executed or none at all.
  • **Consistency:**The data remains consistent before and after executing the transaction. For example, in a money transfer business, the total amount of the transferor and the payee should remain unchanged regardless of whether the transaction is successful or not.
  • **Isolation:**When accessing the database concurrently, a user's transaction should not be affected by other transactions, and the database is independent between concurrent transactions.
  • **Persistence:**After a transaction is committed, its changes to the data in the database are durable and should not be affected even if the database fails.

3. Problems caused by concurrent transactions

In a typical application, multiple transactions run concurrently, often Manipulate the same data to complete their respective tasks (multiple users operating on the same data). Although concurrency is necessary, it may cause the following problems:

  • **Dirty read: **When a transaction is accessing data and has modified it, but it is still The transaction was not submitted. At this time, another transaction also accessed the data and then used the data. Because the modification of the data has not been submitted to the database, the data read by the other transaction is "Dirty Data ", this behavior is "Dirty Read", and operations based on "Dirty Data" may cause problems.
  • Lost of modify: means that when a transaction reads a piece of data, another data also accesses the data, then after the first transaction modifies the data , the second transaction also modified this data. In this way, the modification results in the first transaction are lost. This situation is called Modification loss. For example: transaction 1 reads the data A=20 in the table, transaction 2 also reads A=20, transaction 1 modifies A=A-1, transaction 2 also modifies A=A-1, and the final result is 19, but the modification record of transaction 1 is lost.
  • Unrepeatable read: refers to reading the same data multiple times within a transaction. Before the transaction ends, another transaction also accesses the data and evaluates the data. If the data is modified, the data read twice by the first transaction may be inconsistent. This situation is called non-repeatable read.
  • Phantom read (Phantom read): Phantom read is similar to non-repeatable read. Phantom read refers to a transaction that reads several rows of data. The transaction has not ended yet, and then Another transaction inserts some data. In subsequent queries, the first transaction reads more data than originally read, as if an hallucination has occurred, so it is called phantom reading.

The difference between non-repeatable reading and phantom reading:

The focus of non-repeatable reading is modification, while the focus of phantom reading is addition or deletion.

Chestnut 1 (Same conditions, the data you have read will be different when you read it again): Mr. A in transaction 1 has read that his salary is 1,000. The operation has not ended yet, and the transaction Mr. B in 2 modified Mr. A's salary to 2000. When Mr. A read his salary again, it became 2000. This is a non-repeatable read.

Chestnut 2 (same conditions, the number of records read out for the first and second times is different): If there are 4 people in a salary table with a salary greater than 3,000, transaction 1 reads all For people with a salary greater than 3,000, a total of 4 records were queried. This is because transaction 2 queried another record with a salary greater than 3,000. Transaction 1 read again and found 5 records. This is a phantom read.

4. Transaction isolation levels

The SQL standard defines four isolation levels:

  • **READ-UNCOMMITTED: **The lowest isolation level, allowing reading of uncommitted data changes, may cause dirty reads, non-repeatable reads, and phantom reads.
  • **READ-COMMITTED: **Allows reading of data that has been submitted by concurrent transactions, can avoid dirty reads, but may cause non-repeatable and phantom reads.
  • **Repeatable read (REPEATABLE-READ): **The results of multiple reads of the same field are consistent unless the transaction itself is modified, can avoid dirty reads and unresolved reads Repeated reading may cause phantom reading.
  • **Serializable (SERIALIZABLE): **The highest isolation level, fully compliant with the ACID isolation level, all transactions are executed in sequence, can avoid dirty reads and non-repeatable reads , phantom reading.
##Read submitted×√√##Repeatable readSerializable

MySQL InnoDB The default transaction isolation level of the storage engine is Repeatable Read (REPEATABLE-READ) , which can be obtained through the command select @@tx_isolation; statement View, MySQL 8.0 This statement is changed to SELECT @@transaction_isolation;

mysql> SELECT @@tx_isolation;
+-----------------+
| @@tx_isolation  |
+-----------------+
| REPEATABLE-READ |
+-----------------+
Copy after login

MySQL InnoDBRepeatable read and merge of the storage engine Phantom reads cannot be avoided, and the application needs to use locked reads to ensure that the mechanism used for locked reads is Next-Key Locks.

Because the lower the isolation level, the fewer locks requested by the transaction, so the isolation level of most database systems is READ-COMMITTED , InnoDB The storage engine uses REPEATABLE-READ by default without any performance loss.

InnoDBThe storage engine generally uses the serializable isolation level in the case of distributed transactions.

? Expand (the following content is excerpted from Chapter 7.7 of "MySQL Technology Insider: InnoDB Storage Engine (2nd Edition)"):

The InnoDB storage engine provides support for XA transactions , and supports the implementation of distributed transactions through XA transactions. Distributed transactions refer to allowing multiple independent transaction resources to participate in a global transaction. Transactional resources are typically relational database systems, but can be other types of resources. Global transactions require that all participating transactions must either be committed or rolled back, which further improves the original ACID requirements for transactions. In addition, when using distributed transactions, the transaction isolation level of the InnoDB storage engine must be set to SERIALIZABLE.

4. Actual situation demonstration

MySQLIn the default configuration of the command line, transactions are automatically submitted , that is, executing the SQL statement will immediately execute the COMMIT operation. You can start a transaction with the command START TRANSACTION.

We can set the transaction isolation level through the following command.

SET [SESSION|GLOBAL] TRANSACTION ISOLATION LEVEL [READ UNCOMMITTED|READ COMMITTED|REPEATABLE READ|SERIALIZABLE]
Copy after login

Let’s take a look at some of the concurrency control statements we use in actual operations:

  • START TRANSACTION | BEGIN: Open a transaction explicitly.
  • COMMIT: Commit the transaction, making all modifications to the database permanent.
  • ROLLBACK: Roll back to the end of the user's transaction and undo all uncommitted modifications in progress.

(dirty read) read uncommitted

(Avoid dirty reads) Read committed

##Non-repeatable read

It’s still the read-committed diagram above. Although it avoids reading uncommitted, it does occur. Before a transaction ends, a non-repeatable read problem occurs.

Repeatable reading

[External link image transfer failed, the source site may have anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-ysjbfC4b-1651149978452)(https://qtspace.cn/contentimg/81.jpg)]

phantom reading

Demonstrate the occurrence of phantom reading

sql script 1 When querying the record with a salary of 500 for the first time, there is only one record, sql script 2 inserts A record with a salary of 500 was obtained. After submission, sql script 1 used the current read query again in the same transaction and found that two records with a salary of 500 appeared. This is a phantom read.

There are some similarities between phantom reading and non-repeatable reading, but the focus of non-repeatable reading is modification, while the focus of phantom reading is addition or deletion.

Methods to solve phantom reads

    Adjust the transaction isolation level to
  • SERIALIZABLE.
  • At the repeatable read transaction level, add a table lock to the table in the transaction operation.
  • At the repeatable read transaction level, add
  • Next-Key Locks to the table of the transaction operation.
Description:

Next-Key Locks Equivalent to row lock gap lock

[Related recommendations:

mysql video tutorial

Isolation level Dirty read Non-repeatable read Phantom read
Read Uncommitted
× ×
× × ×

The above is the detailed content of What are the mysql transaction isolation levels?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

How to start mysql by docker How to start mysql by docker Apr 15, 2025 pm 12:09 PM

The process of starting MySQL in Docker consists of the following steps: Pull the MySQL image to create and start the container, set the root user password, and map the port verification connection Create the database and the user grants all permissions to the database

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

How to install mysql in centos7 How to install mysql in centos7 Apr 14, 2025 pm 08:30 PM

The key to installing MySQL elegantly is to add the official MySQL repository. The specific steps are as follows: Download the MySQL official GPG key to prevent phishing attacks. Add MySQL repository file: rpm -Uvh https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm Update yum repository cache: yum update installation MySQL: yum install mysql-server startup MySQL service: systemctl start mysqld set up booting

Centos install mysql Centos install mysql Apr 14, 2025 pm 08:09 PM

Installing MySQL on CentOS involves the following steps: Adding the appropriate MySQL yum source. Execute the yum install mysql-server command to install the MySQL server. Use the mysql_secure_installation command to make security settings, such as setting the root user password. Customize the MySQL configuration file as needed. Tune MySQL parameters and optimize databases for performance.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

See all articles