What is the difference between optimistic locking with version numbers and timestamps?
Why Interviewers Ask This
Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.
Answer
Optimistic locking detects conflicts at write time by verifying the data hasn't changed since it was read. Two common implementations: Version number (integer counter): add a version INT NOT NULL DEFAULT 0 column. On read, fetch the version. On update: UPDATE products SET stock = stock - 1, version = version + 1 WHERE id = ? AND version = ? — check affected rows; 0 means conflict (another transaction already updated and incremented version). Increment version atomically. Advantages: no issues with precision or time synchronization; works reliably even on the same millisecond. Timestamp: add an updated_at DATETIME(6) column (microsecond precision). On update: UPDATE products SET stock = ?, updated_at = NOW(6) WHERE id = ? AND updated_at = ?. Disadvantages: requires microsecond precision to avoid conflicts when two updates happen in the same millisecond (still possible on fast hardware); clock synchronization issues in distributed systems; TIMESTAMP resolution matters. Recommendation: use integer version numbers — they are simpler, unambiguous, and not subject to clock issues. Version-based optimistic locking is natively supported by ORMs like Hibernate, TypeORM (@VersionColumn), and Sequelize (version: true).
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
What is the query execution plan and how does the MySQL optimizer work?
Next
What are common SQL anti-patterns to avoid?
More MySQL / SQL Questions
View all →- Advanced What is the difference between B-tree and Hash indexes in MySQL?
- Advanced What is MVCC (Multi-Version Concurrency Control) in MySQL?
- Advanced What is the InnoDB Buffer Pool and how does it work?
- Advanced What is deadlock in MySQL and how do you prevent it?
- Advanced What is the query execution plan and how does the MySQL optimizer work?