You'll need to execute these actions inside of a transaction (autocommit=0
) because SELECT FOR UPDATE
only holds the lock until the transaction completes.
None of your scenarios occur. The transactions won't immediately fail, but they may time out.
If transaction 2 attempts to lock the same record as transaction 1 (the lock occurs in the SELECT FOR UPDATE
), transaction 2 will have to wait until transaction 1 completes. If the lock time out period (innodb_lock_wait_timeout) is reached, then the transaction will time out ("fail").
Ensure that any time you want to select the record and obey any current locks that you use SELECT FOR UPDATE
. A normal SELECT
without FOR UPDATE
won't wait for any locks.
You should, obviously, attempt to finish any transaction as quickly as possible.
Your method should work fine. You should consider retrieving the primary key value in the SELECT FOR UPDATE
statement and then simply reference the record by the primary key value in the UPDATE
statement.