Interview Q&A / SQL & DBMS

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What is the difference between optimistic and pessimistic locking?

SHORT ANSWER

Pessimistic locking locks the row up front so others must wait, assuming conflicts are likely. Optimistic locking takes no lock and checks at update time, usually with a version number, whether someone else changed the row.

Explain it simply

Pessimistic is like putting a "reserved" board on a library book before you start reading, so nobody else can touch it. Optimistic is reading freely, and at checkout the librarian checks the book's edition number, and if someone changed it meanwhile, asks you to start again.

Example

Pessimistic:

sql
BEGIN;
SELECT stock FROM products WHERE id = 7 FOR UPDATE;  -- row locked
UPDATE products SET stock = stock - 1 WHERE id = 7;
COMMIT;

Optimistic, with a version column:

sql
SELECT stock, version FROM products WHERE id = 7;   -- stock=5, version=3

UPDATE products
SET stock = 4, version = version + 1
WHERE id = 7 AND version = 3;
-- if 0 rows updated, someone else changed it, so re-read and retry
PessimisticOptimistic
Locks heldYes, during the transactionNo
Best whenConflicts are frequentConflicts are rare
Cost of conflictWaiting, possible deadlocksRetry

What to say in the interview

"Pessimistic locking blocks others with SELECT FOR UPDATE. Optimistic uses a version column and a conditional update, detecting conflicts at write time. I pick optimistic for read-heavy, low-conflict workloads and pessimistic for contested rows like a last ticket."

Common mistakes

  • Forgetting to check the affected row count in the optimistic update.

#dbms#transactions#locking#concurrency

Related questions

Practise more SQL & DBMS questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open SQL & DBMS quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.