Interview Q&A · SQL · 10 questions in this topic
Transactions & Concurrency — SQL Interview Q&A
Correct concurrent writes — ACID, isolation levels, locking and the lost-update defenses. Part of Indexes & Transactions · 192 questions in the SQL bank.
What is a transaction (BEGIN / COMMIT / ROLLBACK)?
Answer
A transaction bundles statements into one atomic unit: all commit together (COMMIT) or all roll back (ROLLBACK) — no partial writes. BEGIN starts explicitly (autocommit otherwise commits per statement); SAVEPOINTs allow partial rollbacks inside.
Multi-statement writes without transactions are partial-failure bugs by construction.
Example
BEGIN; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT; -- both or neither
💡 All-or-nothing is the atomicity sentence.
What does ACID mean?
Answer
Atomicity (all-or-nothing commits), Consistency (constraints hold before and after), Isolation (concurrent transactions do not see each other's partial work), Durability (committed data survives crashes via WAL). Together they make concurrent writes sane.
One letter per guarantee with a one-line example each is the complete answer.
Key points
- 1Atomicity — COMMIT all or ROLLBACK all.
- 2Consistency — invariants preserved.
- 3Isolation — no partial visibility.
- 4Durability — WAL-backed survival.
What are the isolation levels (READ COMMITTED to SERIALIZABLE)?
Answer
READ UNCOMMITTED (dirty reads — mostly theoretical in PostgreSQL), READ COMMITTED (no dirty reads; default in PostgreSQL), REPEATABLE READ (snapshot-stable reads; snapshot isolation in PostgreSQL), SERIALIZABLE (serial-order guarantee, aborts on conflicts). Higher isolation costs concurrency and retries.
Anomalies prevented per level (dirty/non-repeatable/phantom) is the comparison grid.
Key points
- 1READ COMMITTED — statement snapshots, default.
- 2REPEATABLE READ — transaction snapshot.
- 3SERIALIZABLE — serial equivalence, retry on abort.
Example
-- PostgreSQL: BEGIN ISOLATION LEVEL REPEATABLE READ;
💡 Anomaly-per-level is the grid interviewers expect.
What are dirty reads, non-repeatable reads and phantom reads?
Answer
Dirty read: seeing uncommitted data (rolled back later — never happened). Non-repeatable: re-reading a row mid-transaction finds changed values. Phantom: re-running a range query finds new rows. Isolation levels exist precisely to forbid chosen subsets.
Name one scenario per anomaly — concurrent transfer, report re-read, range recount.
Key points
- 1Dirty — uncommitted visibility.
- 2Non-repeatable — changed re-read.
- 3Phantom — new matching rows.
How do locks work (row, table, SELECT FOR UPDATE)?
Answer
Writers take row locks; DDL takes strong table locks; SELECT ... FOR UPDATE locks chosen rows for the transaction (pessimistic guard for read-modify-write). NOWAIT/SKIP LOCKED variants avoid blocking (queue-skipping patterns). Deadlocks abort with retryable errors.
Lock explicitly for multi-statement invariants; prefer atomic statements otherwise.
Example
BEGIN; SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; -- modify, then COMMIT (lock released)
💡 Pessimistic-guard-for-invariants is the FOR UPDATE framing.
What is optimistic locking (version columns)?
Answer
Each row carries a version incremented per write; updates include AND version = :expected — zero rows affected means someone else wrote first (retry with fresh data). No locks held, works across app servers and long user think-times.
Pessimistic locks for short transactions; versions for contention-light business entities.
Example
UPDATE accounts SET balance = 90, version = 6 WHERE id = 1 AND version = 5; -- 0 rows = conflict
💡 Zero-rows-means-conflict is the mechanism sentence.
What is MVCC (multi-version concurrency control)?
Answer
Writers create new row versions instead of overwriting — readers see snapshot-appropriate versions without blocking writers (PostgreSQL, InnoDB). Old versions become dead tuples reclaimed by VACUUM/purge. Snapshots give repeatable reads cheaply; version chains are the storage cost.
Readers-never-block-writers is the MVCC headline.
Key points
- 1Versions — writes create, never overwrite in place.
- 2Snapshots — reads pick version by time.
- 3Cleanup — VACUUM reclaims the dead.
What is a deadlock in the database (and how do you handle it)?
Answer
Two transactions holding locks the other wants — the engine detects the cycle, aborts one with a deadlock error, the app retries the whole transaction. Prevention: consistent lock order (parent before child, id order), short transactions, low isolation where sufficient.
Retryable-abort plus ordered-locking is the complete handling story.
Example
-- always lock accounts in id order, both code paths
💡 Order-locks plus retry-aborts is the doctrine in one line.
How do you transfer money safely between accounts (the classic)?
Answer
Single transaction, row locks in id order (deadlock-proof), balance CHECK constraint (no negatives), RETURNING for confirmation, retry loop on serialization/deadlock errors. The constraint — not application math — is the final guard.
This answer demonstrates transactions, locking order, constraints and retries in one scenario.
Example
BEGIN; SELECT balance FROM accounts WHERE id IN (1,2) ORDER BY id FOR UPDATE; UPDATE accounts SET balance = balance - 100 WHERE id = 1; UPDATE accounts SET balance = balance + 100 WHERE id = 2; COMMIT;
💡 Order-locks, constrain, retry is the money-transfer checklist.
What is autocommit and when do you turn it off?
Answer
Autocommit wraps every statement in its own transaction — convenient, but multi-statement work loses atomicity. Turn it off (explicit BEGIN) for any all-or-nothing sequence: transfers, multi-table writes, guarded updates.
Single statements: autocommit is fine. Sequences: transact explicitly.
Example
-- psql: \set AUTOCOMMIT off (or always use explicit BEGIN)
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission