How to lock a row for select in MySQL

Allen Koo picture Allen Koo · Mar 17, 2013 · Viewed 7.6k times · Source

A program will SELECT several records from a table and update each row, while it can be executed many times, which will lead to several process will complete the same task simultaneously.

How can I prevent two different processes to update the same row in the table. That's to say, how can I ensure each process can SELECT different records? Is there any locks on row-select level in MySQL? Or in this situation, is there any better solution to prevent a single row updating for many times?

Answer

mjuarez picture mjuarez · Mar 17, 2013

You can use a SELECT FOR UPDATE. Inside your transaction, start out selecting the rows that you want to "lock", something like this:

 SELECT * from TABLE where id = 123 FOR UPDATE;

If two different transactions try to do this at the same time, MySQL will make the second one wait until the first one has committed the transaction. That way, you'll be assured that the second transaction only looks at the row after the first one is done with it.