MySQL ‘select for update’ behaviour

Let me go through your cases and explain how these locks work:

1 case

T1 wants to update some rows in your test table. This transaction puts IX lock on all table and X lock on the first 5 rows.

T2 wants to update some rows in your test table. This transaction puts IX (because IX compatible with IX) lock on all table and tries to first 5 rows but it can’t do it because X is not compatible with X

So we are fine.

2.1 case

T1 wants to update some rows in your test table. This transaction put IX lock on all table and X lock on the first 5 rows.

T2 wants to select some rows from your test table. And it does not place any locks (because InnoDB provides non-locking reads)

2.1 case

T1 wants to update some rows in your test table. This transaction put IX lock on all table and X lock on the first 5 rows.

T2 wants to update (select for update)some rows from your test table. Place IS on the whole table and tries to get S lock on the row and fails because X and S are uncompatible.


Also always be aware of isolation level: different level cause different mechanism to free/acquire locks

Hope it helps

Leave a Comment