1 Understanding Locks
TopBuilding on Transactions & Concurrency, locks are the mechanism databases use to prevent concurrent transactions from corrupting each other's data.
Lock Types
| Lock Type | Also Called | Who Can Read? | Who Can Write? | Use Case |
|---|---|---|---|---|
| Shared (S) | Read lock | Everyone | No one (until released) | SELECT queries |
| Exclusive (X) | Write lock | Only the holder | Only the holder | INSERT, UPDATE, DELETE |
| Update (U) | Intent-to-write | Everyone | Only the holder (upgrades to X) | SELECT...FOR UPDATE |
Lock Granularity
| Level | What's Locked | Concurrency | Overhead |
|---|---|---|---|
| Row-level | Individual rows | High — other rows accessible | More memory per lock |
| Page-level | A page (group of rows) | Medium | Medium |
| Table-level | Entire table | Low — blocks all access | Minimal overhead |
-- Explicitly lock rows for update
START TRANSACTION;
SELECT balance FROM accounts
WHERE id = 1
FOR UPDATE; -- Exclusive lock on this row
-- Other transactions trying to read/write row id=1 will WAIT
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
COMMIT; -- Lock released-- Shared lock (read without blocking other readers)
SELECT balance FROM accounts
WHERE id = 1
LOCK IN SHARE MODE; -- MySQL syntaxInnoDB (MySQL default): Uses row-level locking by default. This means two users can update different rows in the same table simultaneously. MyISAM uses table-level locking — one of many reasons to always use InnoDB.
Key Takeaways
- Shared locks allow concurrent reads; exclusive locks block everything
-
FOR UPDATEacquires an exclusive lock;LOCK IN SHARE MODEacquires a shared lock - Row-level locking (InnoDB) provides the best concurrency
- Locks are released on COMMIT or ROLLBACK