Mysql Lock Mechanism--The Harm of Gap Lock

 

Mysql series article home page 

 

===============

 

1 Prepare data

1.1 Create a table

DROP TABLE IF EXISTS employee;
CREATE TABLE IF NOT EXISTS employee (
    id INT  PRIMARY  KEY ,
    name VARCHAR(40),
    money INT
)ENGINE INNODB;

1.2 Insert data

INSERT INTO employee(id, name, money) VALUES(1, 'Alice', 10000);
INSERT INTO employee(id, name, money) VALUES(3, 'Bob', 10000);

Tip: Two records with id=1 & id=3 are inserted here, but no record with id=2 is inserted. Why? will be used later.

2 test

2.1 Preparation

Or the old rule, two sessions (terminals), with a white background on the left and a black background on the right, and both set autocommit = 0

2.2 Testing

2.2.1 Perform an update in the left session

Sql statement:

UPDATE employee SET money = money + 10000 WHERE id >= 1 AND id <= 3; 

result:

2.2.2 Perform insert in right session

Sql statement:

INSERT INTO employee(id, name) VALUES(2, 'David');

result:

 

blocked! Caused by gap lock.

2.2.3 Execute commit on the left

Tip: Pay attention to the changes in the execution of the Sql statement in the session on the right

2.2.4 View the session on the right

blocked, took 22.15 seconds

2.2.5 Commit is also performed on the right side

2.2.6 View the results on the left

2.2.7 View the results on the right

The result is the same and as expected.

2.2.8 Analysis & Conclusion

In the update statement on the left, the id range is limited to [1, 3]. When Mysql executes, it will convert all eligible ids in the range (for this example, 1, 2, 3) corresponding to The update operation is locked so that inserting the record with id=2 is blocked.

3 Conclusion

When querying the primary key range, pay attention to gap locks

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324766304&siteId=291194637