search
HomeDatabaseMysql TutorialMySQL's four transaction isolation levels

MySQL's four transaction isolation levels

Dec 15, 2020 am 10:24 AM
mysqlisolation 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
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Adding Users to MySQL: The Complete TutorialAdding Users to MySQL: The Complete TutorialMay 12, 2025 am 12:14 AM

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

Mastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMastering MySQL String Data Types: VARCHAR vs. TEXT vs. CHARMay 12, 2025 am 12:12 AM

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

MySQL: String Data Types and Indexing: Best PracticesMySQL: String Data Types and Indexing: Best PracticesMay 12, 2025 am 12:11 AM

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.

MySQL: How to Add a User RemotelyMySQL: How to Add a User RemotelyMay 12, 2025 am 12:10 AM

ToaddauserremotelytoMySQL,followthesesteps:1)ConnecttoMySQLasroot,2)Createanewuserwithremoteaccess,3)Grantnecessaryprivileges,and4)Flushprivileges.BecautiousofsecurityrisksbylimitingprivilegesandaccesstospecificIPs,ensuringstrongpasswords,andmonitori

The Ultimate Guide to MySQL String Data Types: Efficient Data StorageThe Ultimate Guide to MySQL String Data Types: Efficient Data StorageMay 12, 2025 am 12:05 AM

TostorestringsefficientlyinMySQL,choosetherightdatatypebasedonyourneeds:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseTEXTforlong-formtextcontent.4)UseBLOBforbinarydatalikeimages.Considerstorageov

MySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMySQL BLOB vs. TEXT: Choosing the Right Data Type for Large ObjectsMay 11, 2025 am 12:13 AM

When selecting MySQL's BLOB and TEXT data types, BLOB is suitable for storing binary data, and TEXT is suitable for storing text data. 1) BLOB is suitable for binary data such as pictures and audio, 2) TEXT is suitable for text data such as articles and comments. When choosing, data properties and performance optimization must be considered.

MySQL: Should I use root user for my product?MySQL: Should I use root user for my product?May 11, 2025 am 12:11 AM

No,youshouldnotusetherootuserinMySQLforyourproduct.Instead,createspecificuserswithlimitedprivilegestoenhancesecurityandperformance:1)Createanewuserwithastrongpassword,2)Grantonlynecessarypermissionstothisuser,3)Regularlyreviewandupdateuserpermissions

MySQL String Data Types Explained: Choosing the Right Type for Your DataMySQL String Data Types Explained: Choosing the Right Type for Your DataMay 11, 2025 am 12:10 AM

MySQLstringdatatypesshouldbechosenbasedondatacharacteristicsandusecases:1)UseCHARforfixed-lengthstringslikecountrycodes.2)UseVARCHARforvariable-lengthstringslikenames.3)UseBINARYorVARBINARYforbinarydatalikecryptographickeys.4)UseBLOBorTEXTforlargeuns

See all articles

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 Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools