✏️ Explanatory Question
Level: Advanced — Locking is how MySQL enforces isolation and prevents data corruption under concurrency.
Locking is the mechanism MySQL uses to control concurrent access to data, ensuring that multiple transactions don't interfere with each other and corrupt data. A lock temporarily restricts what other transactions can do to a resource.
| Requesting → | Shared (S) | Exclusive (X) |
|---|---|---|
| Shared (S) held | Compatible | Blocked |
| Exclusive (X) held | Blocked | Blocked |
START TRANSACTION;
-- Acquire a SHARED (read) lock: others can read but not modify
SELECT * FROM accounts WHERE acc_id = 1 LOCK IN SHARE MODE;
-- Acquire an EXCLUSIVE (write) lock: others cannot read or write these rows
SELECT * FROM accounts WHERE acc_id = 1 FOR UPDATE;
UPDATE accounts SET balance = balance - 500 WHERE acc_id = 1;
COMMIT; -- releases the locks
-- Explicit table-level locks
LOCK TABLES accounts WRITE;
-- ... operations ...
UNLOCK TABLES;
LOCK IN SHARE MODE can also be written as FOR SHARE, and both support options like NOWAIT and SKIP LOCKED for non-blocking behaviour.