Consider this situation:
- Begin transaction
- Insert 20 records into a table with an auto_increment key
- Get the first insert id (let’s say it’s
153) - Update all records in that table where
id >= 153 - Commit
Is step 4 safe?
That is, if another request comes in almost precisely at the same time, and inserts another 20 records after step 2 above, but before step 4, will there be a race condition?
Yes, it will.
Records
21to40will be locked by the transaction2.Transaction
1will be blocked and wait until transaction2commits or rolls back.If transaction
2commits, then transaction1will update40records (including those inserted by transaction2)