SQL & Relational Databases (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
What are Pessimistic Locking vs Optimistic Locking?
senior LevelMost AskedCode Examplesql-databasesAdvanced Internals
In Simple Words:
- Pessimistic Locking: Assumes conflicts will happen. Locks the row immediately upon reading using
SELECT ... FOR UPDATE:- Other transactions attempting to modify the row are blocked until commit. High safety, lower concurrency.
- Optimistic Locking: Assumes conflicts are rare. Does not acquire database locks.
- Adds a
version_numbercolumn. - Writes verify version:
UPDATE accounts SET balance = 50, version = version + 1 WHERE id = 1 AND version = 3; - If rows affected is 0, another transaction modified the row; application retries. High throughput for web apps.
- Adds a
sql
-- Optimistic Concurrency Control SQL pattern:
UPDATE products
SET stock_count = stock_count - 1, version = version + 1
WHERE id = 101 AND version = 4;
-- If 0 rows updated -> Conflict detected! Retry.