Row Level Locking

suggest change

If the tables use InnoDB, MySQL uses row locks so that transactions can read and write different rows of the same table without waiting for each other. A plain SELECT does not lock the row.

If two transactions try to modify the same row, one waits for the other to finish.

A locking read is SELECT ... FOR UPDATE on each row you expect to modify.

Consider two connections to explain Row level locking in detail

Connection 1

START TRANSACTION;
SELECT ledgerAmount FROM accDetails WHERE id = 1 FOR UPDATE;

In connection 1, row level lock obtained by SELECT ... FOR UPDATE statement.

Connection 2

UPDATE accDetails SET ledgerAmount = ledgerAmount + 500 WHERE id=1;

When someone tries to update that same row in connection 2, the statement waits for connection 1 to finish, or it fails according to innodb_lock_wait_timeout, which defaults to 50 seconds.

Error Code: 1205. Lock wait timeout exceeded; try restarting transaction

To view details about this lock, run SHOW ENGINE INNODB STATUS

---TRANSACTION 1973004, ACTIVE 7 sec updating
mysql tables in use 1, locked 1
LOCK WAIT 2 lock struct(s), heap size 360, 1 row lock(s)
MySQL thread id 4, OS thread handle 0x7f996beac700, query id 30 localhost root update
UPDATE accDetails SET ledgerAmount = ledgerAmount + 500 WHERE id=1
------- TRX HAS BEEN WAITING 7 SEC FOR THIS LOCK TO BE GRANTED:

Connection 2

UPDATE accDetails SET ledgerAmount = ledgerAmount + 250 WHERE id=2;
1 row(s) affected

Updating a different row from connection 2 runs without waiting.

Connection 1

UPDATE accDetails SET ledgerAmount = ledgerAmount + 750 WHERE id=1;
COMMIT;
1 row(s) affected

The row lock is released because the transaction is committed in connection 1.

Connection 2

UPDATE accDetails SET ledgerAmount = ledgerAmount + 500 WHERE id=1;
1 row(s) affected

The update is executed without any error in Connection 2 after Connection 1 released row lock by finishing the transaction.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents