MySQL Write Lock – Understanding and Managing InnoDB Locking

innodblockingMySQL

I dont add any manual locking or any transaction anything, just manual running queries from php script, and execute below two update queries at the same time

update table_x set status = 'PROCESSING' where id = 123 and status = 'PENDING'

update table_x set status = 'PROCESSING' where id = 123 and status = 'PENDING'

And If I rely on the updated rows count then is it possible that both return 1?

The requirement here is that from my web-server if two processes at
the same time try to process same row then I have to avoid both
processing it.

In a solution where I first run a select query to check if the status for the given id is PENDING and then do the processing, there is a chance of both processing it.

But I'm not sure what will happen if I do just one update query and rely on the rows updated count.

Best Answer

No problem. Use InnoDB.

One of those queries will take out an "exclusive" lock on the row in question. The other query will try to take out such a lock, but be blocked until the first finishes (and COMMITs). Then it will see that there is no longer any row matching the WHERE clause, so it will say "0 rows matched, 0 rows updated".