While troubleshooting deadlocks for a customer, I came around an interesting situation involving InnoDB gap locks. For a non-INSERT write operation where the WHERE clause does not match any row, I expected there should’ve been no locks to be held by the transaction, but I was wrong. Let’s take a look at this table and and example UPDATE.

InnoDB status shows that this UPDATE holds an X lock on a PRIMARY index record:

For the why, Heikki explained on this aging bug report, which makes sense and I understand the fix can be difficult, though at the same time a bit annoying I wished it was handled differently. To complete this post, let me demonstrate the deadlock situation I was telling about earlier mysql1 for first session and mysql2 for the second, the order of queries apply:

So you see how easy it is to cause a deadlock, so make sure to avoid this situation – if a non-INSERT write operation is more likely to not match any row because the INSERT part is yet to come on the transaction, don’t do it or use REPLACE INTO or use READ-COMMITTED transaction isolation.

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Peter Zaitsev

Jervin,

So are you saying REPLACE INTO would not have set the lock in this case ? Why is its handling different ?

Also you mention it does not happen with READ-COMMITTED. Is it the case with both ROW and STATEMENT replication modes ?

ferny

Yo mean REPLACE INTO does not create gap lock?