How to prevent a race condition in MySQL database when two connections want to update the same record?
For example, connection 1 wants to increase “tries” counter. And the second connection wants to do the same. Both connections SELECT the “tries” count, increase the value and both UPDATE “tries” with the increased value. Suddenly “tries” is only “tries+1” instead of being “tries+2”, because both connections got the same “tries” and incremented it by one.
How to solve this problem?
Here’s 3 different approaches:
Atomic update
and it will be done atomically.
Use row locking
If you do need to first select the value and update it in your application, you likely need to use row locking. That means you’ll have to use InnoDB, not MyISAM tables.
Your query would be something like:
All other queries trying to read the same row will have to wait, until the table gets updated, and they will return the updated value.
Version scheme
A common approach is to introduce a version column in your table. Your queries would do something like:
If that update fails/returns 0 rows affected, someone else has updated the table in the mean time. You have to start all over – that is, select the new values, do the application logic and try the update again.