Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Next-Key lock is called this way?

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'?

like image 815
GProst Avatar asked Jun 30 '19 22:06

GProst


People also ask

What is next key lock?

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.

What is row locking in MySQL?

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.

How do MySQL locks work?

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.


1 Answers

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.

like image 70
Bill Karwin Avatar answered Oct 07 '22 18:10

Bill Karwin