Tech Interview RoomStudy guides

SQL Fundamentals

Explain ACID, transaction isolation levels and the anomalies they prevent.

Intermediate · 2 min read · Lesson 5 of 8 in SQL Fundamentals

ACID

  • Atomicity: all statements in a transaction succeed or none do (rollback).
  • Consistency: constraints (keys, checks, foreign keys) hold before and after.
  • Isolation: concurrent transactions do not see each other's intermediate states, to a configurable degree.
  • Durability: once committed, data survives a crash (write-ahead log, redo log).

Read anomalies

  • Dirty read: reading another transaction's uncommitted change.
  • Non-repeatable read: reading the same row twice gives different values because someone committed in between.
  • Phantom read: re-running a query returns new rows that someone inserted.
  • Lost update / write skew: two transactions read, then both write based on stale data.

Isolation levels (SQL standard)

  • Read Uncommitted: allows dirty reads (PostgreSQL treats it as Read Committed).
  • Read Committed: no dirty reads. Default in PostgreSQL, Oracle and SQL Server.
  • Repeatable Read: no non-repeatable reads. Default in MySQL InnoDB, which also blocks most phantoms with next-key locks; PostgreSQL's Repeatable Read is snapshot isolation.
  • Serializable: behaves as if transactions ran one at a time. PostgreSQL implements it with SSI and aborts conflicting transactions, so the application must retry.

Most databases use MVCC (multi-version concurrency control): readers see a consistent snapshot and do not block writers.

Example

sql
-- Preventing a lost update when two users buy the last item
BEGIN;
SELECT stock FROM products WHERE id = 7 FOR UPDATE;   -- locks the row until commit
UPDATE products SET stock = stock - 1 WHERE id = 7 AND stock > 0;
INSERT INTO order_items (order_id, product_id, qty) VALUES (1001, 7, 1);
COMMIT;

-- Alternative without explicit locks: optimistic concurrency with a version column
UPDATE products
SET stock = stock - 1, version = version + 1
WHERE id = 7 AND version = 12 AND stock > 0;   -- 0 rows updated means someone else won: retry

In Spring, the second pattern is JPA's @Version optimistic locking, and the first is @Lock(PESSIMISTIC_WRITE).

Follow-up questions interviewers ask

Try answering each one before you open it.

What is a deadlock and how do you avoid one?

Two transactions each hold a lock the other needs, so neither can continue; the database detects it and aborts one (which must retry). Avoid deadlocks by acquiring locks in a consistent order (for example by ascending id), keeping transactions short, and indexing foreign keys and the columns in WHERE clauses so fewer rows are locked.