Home Database Mysql Tutorial MySQL's four transaction isolation levels

MySQL's four transaction isolation levels

Dec 15, 2020 am 10:24 AM
mysql isolation level

mysql tutorialThe column introduces four transaction isolation levels

MySQL's four transaction isolation levels

Recommended (free): mysql tutorial

The test environment for this article’s experiment: Windows 10 cmd MySQL5.6.36 InnoDB

1. Basic elements of transactions (ACID)

 1. Atomicity: After the transaction starts, all operations are either completed or not. When doing something, it is impossible to stagnate in the middle. If an error occurs during transaction execution, it will be rolled back to the state before the transaction started, and all operations will be as if they did not happen. That is to say, affairs are an indivisible whole, just like atoms learned in chemistry, which are the basic units of matter.

 2. Consistency: Before and after the transaction starts and ends, the integrity constraints of the database are not destroyed. For example, if A transfers money to B, it is impossible for A to deduct the money but B not to receive it.

3. Isolation: At the same time, only one transaction is allowed to request the same data, and there is no interference between different transactions. For example, A is withdrawing money from a bank card. B cannot transfer money to this card before A's withdrawal process is completed.

4. Durability: After the transaction is completed, all updates to the database by the transaction will be saved to the database and cannot be rolled back.

2. Transaction concurrency issues

1. Dirty read: Transaction A reads the data updated by transaction B, and then B rolls back operation, then the data read by A is dirty data

2. Non-repeatable reading: transaction A reads the same data multiple times, and transaction B reads the same data multiple times in transaction A , the data was updated and submitted, resulting in inconsistent results when transaction A read the same data multiple times.

3. Phantom reading: System administrator A changed the scores of all students in the database from specific scores to ABCDE grades, but system administrator B inserted a specific score at this time record. When system administrator A completed the modification, he found that there was still one record that had not been modified. It was as if he had hallucinated. This is called phantom reading.

Summary: Non-repeatable reading and phantom reading are easily confused. Non-repeatable reading focuses on modification, while phantom reading focuses on adding or deleting. To solve the problem of non-repeatable reading, you only need to lock the rows that meet the conditions. To solve the problem of phantom reading, you need to lock the table

3. MySQL transaction isolation level

##Read-uncommittedYesYesYesNon-repeatable read (read-committed)NoYesYesRepeatable-readNoNoYesSerializableNoNoNo

The default transaction isolation level of mysql is repeatable-read

4. Use examples to illustrate each isolation level

1. Read uncommitted:

  (1) Open a client A, and set the current transaction mode to read uncommitted (uncommitted read), query the initial value of the table account:

    (2) Before client A's transaction is committed, open another client B and update the table account:

                       The transaction has not yet been submitted, but client A can query the updated data of B:

  (4) Once client B's transaction is rolled back for some reason , all operations will be revoked, and the data queried by client A is actually dirty data:

                                       luck rid us] The data queried by client A is actually dirty data: set balance = balance - 50 where id =1, lilei's balance did not become 350, but actually 400. Isn't it strange? The data is inconsistent. If you think so, you are too naive. In the application, we will use 400 -50=350, I don’t know that other sessions have been rolled back. To solve this problem, you can use the read-committed isolation level

 2. Read-committed

  (1) Open a client A, and set the current transaction mode to read committed (read committed), query all records of the account table:

   ( 2) Before the transaction of client A is submitted, open another client B and update the table account:

  (3) At this time, the transaction of client B has not yet been completed Submit, client A cannot query the updated data of B, solving the dirty read problem:

  (4) Client B’s transaction submission

 (5) Client A executes the same query as the previous step, but the result is inconsistent with the previous step, which causes a non-repeatable read problem

3. Repeatable read

​ (1) Open a client A, set the current transaction mode to repeatable read, and query all records of the account table

                      All records of the account are consistent with the query results in step (1), and there is no non-repeatable read problem

##  (4) On client A, then execute update balance = balance - 50 where id = 1, the balance does not become 400-50=350, lilei's balance value is calculated using the 350 in step (2), so it is 300, and the consistency of the data is not destroyed. The MVCC mechanism is used under the repeatable read isolation level. The select operation does not update the version number, but is a snapshot read (historical version); insert, update, and delete will update the version number and is a current read (current version).

(5) Re-open client B, insert a new data and submit

(6) In the client End A queries all the records in the account table, and no new data is found, so there is no phantom reading

## 4. Serialization

 (1) Open a client A, set the current transaction mode to serializable, and query the initial value of table account:

 (2) Open a client B and set the current transaction mode to serializable. When inserting a record, an error is reported. The table is locked and the insertion fails. When the transaction isolation level in mysql is serializable, the table will be locked, so phantom reads will not occur. In this case, this isolation level has extremely low concurrency and is rarely used in development.

 Supplement:

 1. When the transaction isolation level is read-commit, writing data will only lock the corresponding row

 2. When the transaction isolation level is repeatable read, if the search condition has an index (including the primary key index), the default locking method is next-key lock; if the search condition There is no index, and the entire table will be locked when updating data. A gap is locked by a transaction, and other transactions cannot insert records in this gap, thus preventing phantom reads.

 3. When the transaction isolation level is serialization, reading and writing data will lock the entire table

 4. The higher the isolation level, the more complete and consistent the data can be guaranteed, but the greater the impact on concurrency performance.

5. MYSQL MVCC implementation mechanism reference link: https://blog.csdn.net/whoamiyang/article/details/51901888

6. Regarding the next-key lock, please refer to the link: https://blog.csdn.net/bigtree_3721/article/details/73731377

Transaction isolation level Dirty read Non-repeatable read Phantom read

The above is the detailed content of MySQL's four 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP's big data structure processing skills PHP's big data structure processing skills May 08, 2024 am 10:24 AM

Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

How to use MySQL backup and restore in PHP? How to use MySQL backup and restore in PHP? Jun 03, 2024 pm 12:19 PM

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

How to optimize MySQL query performance in PHP? How to optimize MySQL query performance in PHP? Jun 03, 2024 pm 08:11 PM

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to insert data into a MySQL table using PHP? How to insert data into a MySQL table using PHP? Jun 02, 2024 pm 02:26 PM

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values ​​to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

How to use MySQL stored procedures in PHP? How to use MySQL stored procedures in PHP? Jun 02, 2024 pm 02:13 PM

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

How to create a MySQL table using PHP? How to create a MySQL table using PHP? Jun 04, 2024 pm 01:57 PM

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

The difference between oracle database and mysql The difference between oracle database and mysql May 10, 2024 am 01:54 AM

Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.

See all articles