当前位置:网站首页>Record the range of data that MySQL update will lock
Record the range of data that MySQL update will lock
2022-06-24 23:11:00 【pythonxxoo】
High quality resource sharing
| Learning route guidance ( Click unlock ) | Knowledge orientation | Crowd positioning |
|---|---|---|
| 🧡 Python Actual wechat ordering applet 🧡 | Progressive class | This course is python flask+ Perfect combination of wechat applet , From the deployment of Tencent to the launch of the project , Create a full stack ordering system . |
| Python Quantitative trading practice | beginner | Take you hand in hand to create an easy to expand 、 More secure 、 More efficient quantitative trading system |
Catalog * 1、 background
- 2、 Pre knowledge
- 3、 Reference link
1、 background
In the project , We often use update sentence , that update Statement will lock the records in the table ? Here we use some simple cases to simulate . Here is my own understanding , If that place is misunderstood , Welcome to point out
2、 Pre knowledge
2.1 Isolation level of database
mysql> show variables like 'transaction\_isolation';
+-----------------------+-----------------+
| Variable_name | Value |
+-----------------------+-----------------+
| transaction_isolation | REPEATABLE-READ |
+-----------------------+-----------------+
1 row in set (0.00 sec)
2.2 Database version
mysql> select version();
+-----------+
| version() |
+-----------+
| 8.0.28 |
+-----------+
1 row in set (0.00 sec)
2.3 Database storage engine
mysql> show variables like '%storage\_engine%';
+---------------------------------+-----------+
| Variable_name | Value |
+---------------------------------+-----------+
| default_storage_engine | InnoDB |
| default_tmp_storage_engine | InnoDB |
| disabled_storage_engines | |
| internal_tmp_mem_storage_engine | TempTable |
+---------------------------------+-----------+
4 rows in set (0.01 sec)
2.4 Is the lock on the record or on the index
The lock is added to the index , If there is no index in the table , Is it added to the table ? It's not , It is also added to the index , There will be a default .
Record locks always lock index records, even if a table is defined with no indexes. For such cases, InnoDB creates a hidden clustered index and uses this index for record locking
Reference link : https://dev.mysql.com/doc/refman/8.0/en/innodb-locking.html#innodb-intention-locks
2.5 update…where The basic unit of locking is
UPDATE ... WHERE ... sets an exclusive next-key lock on every record the search encounters
Here we can understand that the unit of locking is : next-key lock
2.6 Row-level locks
2.6.1 Record Locks
Record locks , That is, only one record will be locked . In fact, it locks the index of this record .A record lock is a lock on an index record. For example, SELECT c1 FROM t WHERE c1 = 10 FOR UPDATE; prevents any other transaction from inserting, updating, or deleting rows where the value of t.c1 is 10.
2.6.2 Gap Locks
Clearance lock , A gap lock is a lock on the gap between index records , That is, lock an interval . Front and back sections , Not including the record itself .
Clearance lock If using Single column unique index value To update , Yes. degeneration become Record Lock.
The purpose of the clearance lock :
- Prevent new data from being inserted into the gap
- Prevent existing data from being updated into the gap .
Gap locking is not needed for statements that lock rows using a unique index to search > for a unique row. (This
does not includethe case that the search condition includes only > some columns of amultiple-column unique index; in that case, gap locking does occur.)
2.6.3 Next-Key Locks
Next-Key Lock yes On the index record Of Record locks and Before indexing records Of Clearance lock on clearance The combination of . It also locks a section , Front open back close interval . Including the record itself .
If the index value includes 1,5,10,30, that next key The lock may cover the following sections
(negative infinity, 1]
(1, 115
(5, 10]
(10, 30]
(30, positive infinity)
negative infinity It means negative infinity .positive infinity It means positive infinity .
2.6.4 Test the table structure of the lock table
create table test_record_lock
(
id int not null comment ' Primary key ',
age int null comment ' Age , General index ',
name varchar(10) null comment ' full name , No index ',
constraint test_record_lock_pk
primary key (id)
)
comment ' Test record lock ';
create index test_record_lock_age_index
on test_record_lock (age);
2.6.5 Test data in table
mysql> select * from test_record_lock;
+----+------+--------+
| id | age | name |
+----+------+--------+
| 1 | 10 | Zhang San |
| 5 | 20 | Li Si |
| 8 | 25 | Wang Wu |
+----+------+--------+
3 rows in set (0.00 sec)
2.7 View the current lock in the database
select * from performance_schema.data_locks;
Field explanation :
| Field | value | explain |
|---|---|---|
lock_type | TABLE | The lock is on the watch |
| RECORD | Lock the record | |
lock_mode | IX | Intention exclusive lock |
| X perhaps S | next-key lock Lock the record itself and the gap before the record | |
| X,REC_NOT_GAP | Record Lock Lock only the record itself | |
| S,REC_NOT_GAP | Record Lock Lock only the record itself | |
| X,GAP | gap lock | |
| X,INSERT_INTENTION | Insert intention lock | |
lock_data | A specific number | Represents the value of the primary key |
| value , value | The first value is : Value of normal index second value : Primary key value |
doubt :X,GAP Can it be understood as X The lock degenerated into GAP lock .
3、 Test data is locked
3.1 Unique index test
This applies to the unique index of a single field , Not suitable for a unique index of multiple fields
3.1.1 Equivalent update - Records exist

explain :
- Add next-key lock, Then the locked record range is (1,5].
- Because it's the only index , And the query value exists ,next-key lock Degenerate into record lock, That is to say, in the end, only id=5 This line of data . The rest of the data does not affect .
3.1.2 Equivalent query - Record does not exist -01

explain :
- Add next-key lock, Then the locked record range is (5,8].
- Because it's the only index , And the query value does not exist ,next-key lock Degenerate into gap, That is, the final locked data range is (5,8). The rest of the data does not affect .
3.1.3 Equivalent update - Record does not exist -02

3.1.4 Scope update
1、 Less than or equal to the maximum critical value

At this point, you can find that all the scanned records in the table have been added next key lock( Lock on index )
2、 Greater than or equal to the minimum critical value
mysql> begin;
Query OK, 0 rows affected (0.01 sec)
mysql> update test_record_lock set name = 'aaa' where id >= 1;
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3 Changed: 3 Warnings: 0
mysql> select LOCK_TYPE,INDEX_NAME,LOCK_MODE,LOCK_DATA from performance_schema.data_locks;
+-----------+------------+---------------+------------------------+
| LOCK_TYPE | INDEX_NAME | LOCK_MODE | LOCK_DATA |
+-----------+------------+---------------+------------------------+
| TABLE | NULL | IX | NULL |
| RECORD | PRIMARY | X,REC_NOT_GAP | 1 |
| RECORD | PRIMARY | X | supremum pseudo-record |
| RECORD | PRIMARY | X | 8 |
| RECORD | PRIMARY | X | 5 |
+-----------+------------+---------------+------------------------+
5 rows in set (0.01 sec)
Only records smaller than the minimum threshold can be inserted into the table .
3、 normal range

3.2 General index test
3.2.1 Equivalent update - Records exist

explain :
- First, the general index
ageadd next-key lock, The scope of locking is (10,20] - next-key lock And lock this record , So in id The value of the index is equal to 5 Added Record Lock
- Because it is a normal index and the value still exists , Therefore, a clearance lock will be added to the next section of this record Gap Lock, The locked range is (20,25)
3.2.2 Equivalent update - Record does not exist

explain :
- obtain next-key lock The locked range is (10,20]
- Because the record to be updated does not exist ,next-key lock Degenerate into gap lock, So the locked range is (10,20)
- Because it is a normal index and the record does not exist , So there is no need to find the next interval again .
3.2.3 Scope update

explain :
- Range update of normal index ,next-key-lock It does not degenerate into gap lock.
3.3 No index update

It can be seen from the above figure , Updating data tables without indexes is dangerous , It needs to be handled with care . No index update , Causes a full table scan , This causes all the scanned records to be added with next-key lock.
3、 Reference link
1、https://dev.mysql.com/doc/refman/8.0/en/innodb-locking.html#innodb-intention-locks
2、https://dev.mysql.com/doc/refman/8.0/en/innodb-locking.html
边栏推荐
- . Net 7 Preview 1 has been officially released
- 研究生宿舍大盘点!令人羡慕的研究生宿舍来了!
- High level application of SQL statements in MySQL database (I)
- [text data mining] Chinese named entity recognition: HMM model +bilstm_ CRF model (pytoch) [research and experimental analysis]
- Research and investment strategy report on China's nano silver wire conductive film industry (2022 Edition)
- 【nvm】
- Financial management [1]
- 推送Markdown格式信息到钉钉机器人
- China smallpox vaccine market trend report, technical innovation and market forecast
- Building Survey [1]
猜你喜欢

「ARM 架构」是一种怎样的处理器架构?

花房集团二次IPO:成于花椒,困于花椒

Docker installation MySQL simple without pit

2022 simulated 100 questions and simulated examination of high-altitude installation, maintenance and demolition

02_ Springboot starter case

Attention, postgraduate candidates! They are the easiest scams to get caught during the preparation period?!

Canvas to add watermark to pictures

2022 safety officer-b certificate examination question bank and answers

【武汉大学】考研初试复试资料分享

Dynamic menu, auto align
随机推荐
How to submit the shopee opening and settlement flow?
Research Report on market supply and demand and strategy of ceiling power supply device industry in China
go Cobra命令行工具入门
01_SpingBoot 框架入门
Financial management [6]
Simulated 100 questions and online simulated examination of high voltage electrician examination in 2022
shopee开店入驻流水如何提交?
对抗训练理论分析:自适应步长快速对抗训练
Mycms we media CMS V3.0, resource push optimization, new free template
Memory alignment of structures
[postgraduate entrance examination English] prepare for 2023, learn list8 words
Leetcode algorithm The first common node of two linked lists
[postgraduate entrance examination English] prepare for 2023, learn list9 words
High level application of SQL statements in MySQL database (I)
力扣解法汇总515-在每个树行中找最大值
[WSL] SSH Remote Connection and host port forwarding configuration
Building Survey [1]
07_SpingBoot 实现 RESTful 风格
Epics record reference 2 -- epics process database concept
Leetcode algorithm refers to offer II 027 Palindrome linked list