As I understand (basing on official docs), Next-Key lock is an index record lock + the gap lock BEFORE that index record (preceding gap).
So I'm curious why is it called NEXT-Key lock? What 'key' is meant here and why 'next'?
A next-key lock is a combination of a record lock on the index record and a gap lock on the gap before the index record. InnoDB performs row-level locking in such a way that when it searches or scans a table index, it sets shared or exclusive locks on the index records it encounters.
Sets a shared mode lock on any rows that are read. Other sessions can read the rows, but cannot modify them until your transaction commits. If any of these rows were changed by another transaction that has not yet committed, your query waits until that transaction ends and then uses the latest values.
A MySQL Locks is nothing but a flag that can be assigned to a table to alter its properties. MySQL allows a table lock that can be assigned by a client-server to prevent other sessions from being able to access the same table during a specific time frame.
In this context, key means one entry in an index. So one can say, "a key is locked" which means some session holds a lock on an entry in the index.
A next-key lock is acquired by index searches or scans.
UPDATE mytable WHERE id > 18;
Suppose there are actually values in the index 10, 11, 13, and 20 (like in the example in that manual). The UPDATE shown above would lock the entry for 20, and the gap before 20, because it's an index scan.
Then your session tries to insert into the gap:
INSERT INTO mytable (id) VALUES (19);
This conflicts with the gap-lock part of the next-key lock.
Think of it this way: you can't get the lock on 19, because some other session already has locked the gap that includes the value 19 you want to insert, as well as 20, which is the next key after 19 that really exists in the index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With