Search code examples
mysqldatabasetransactionsinnodbselect-for-update

Why use SELECT FOR UPDATE? (MySQL)


I have a question regarding what purpose we are using SELECT FOR UDPATE? What does it do exactly?

I have 2 tables, from that I need to select rows from table and update the same rows.

For example:

Select Query

SELECT * from  t1 WHERE city_id=2 for update

Update Query

UPDATE t1 SET final_balance = final_balance - 100 WHERE city_id ='2'

My question - Does this really lock the read operation till my update is done, or what does it exactly deal with?

My idea is nobody can read/update from/to these rows until my update finished.


Solution

  • SELECT ... FOR UPDATE will lock the record with a write (exclusive) lock until the transaction is completed (committed or rolled back).

    To select a record and ensure that it's not modified until you update it, you can start a transaction, select the record using SELECT ... FOR UPDATE, do some quick processing, update the record, then commit (or roll back) the transaction.

    If you use SELECT ... FOR UPDATE outside of a transaction (autocommit ON), then the lock will still be immediately released, so be sure to use a transaction to retain the lock.

    For performance, do not keep transactions open for very long, so the update should be done immediately.