EmergencyEMERGENCY? Get 24/7 Help Now!

One more InnoDB gap lock to avoid

 | December 12, 2013 |  Posted In: Insight for DBAs, MySQL, Percona MySQL Support


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.

Jervin Real

As Senior Consultant, Jervin partners with Percona's customers on building reliable and highly performant MySQL infrastructures while also doing other fun stuff like watching cat videos on the internet. Jervin joined Percona in Apr 2010.


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

  • @Peter, @ferny,

    REPLACE INTO sets the same lock, but in the context of the deadlock example I gave, it prevents premature locking in turn avoiding the deadlock. Also, READ-COMMITTED only works with ROW binlog format.

Leave a Reply


Percona’s widely read Percona Database Performance blog highlights our expertise in enterprise-class software, support, consulting and managed services solutions for both MySQL® and MongoDB® across traditional and cloud-based platforms. The decades of experience represented by our consultants is found daily in numerous and relevant blog posts.

Besides specific database help, the blog also provides notices on upcoming events and webinars.
Want to get weekly updates listing the latest blog posts? Subscribe to our blog now! Submit your email address below and we’ll send you an update every Friday at 1pm ET.

No, thank you. Please do not ask me again.