If the tables use InnoDB, MySQL automatically uses row level locking so that multiple transactions can use same table simultaneously for read and write, without making each other wait.
If two transactions trying to modify the same row and both uses row level locking, one of the transactions waits for the other to complete.
Row level locking also can be obtained by using SELECT ... FOR UPDATE
statement for each rows expected to be modified.
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 some one try to update same row in connection 2, that will wait for connection 1 to finish transaction or error message will be displayed according to the innodb_lock_wait_timeout
setting, 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
But while updating some other row in connection 2 will be executed without any error.
Connection 1
UPDATE accDetails SET ledgerAmount = ledgerAmount + 750 WHERE id=1;
COMMIT;
1 row(s) affected
Now row lock is released, because transaction is commited 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.