// free study notes

SQL transactions & concurrency interview questions

Transactions questions move fast from definitions to debugging: which anomaly your default level lets through, why the deadlock victim died, and what an idle-in-transaction session is costing. Every answer names where the engines differ.

12 questions
  • 3 easy
  • 7 medium
  • 2 hard
Practice mode: all topics, shuffled

What this page covers

  • 12 questions on transactions & concurrency, tagged easy, medium or hard, each with a worked answer in runnable SQL.
  • One schema throughout. The answers use the small shop schema shown here. Dialect-specific examples name the engine they are written for, and the few extra tables a question needs, such as subscribers or logins, are introduced where they appear.
  • Practice mode. To test yourself first, press Hide answers: each answer waits behind a Show answer button. The practice mode link deals a shuffled deck from every topic.
The shop schema
customers(customer_id, name, city, signup_date)
orders(order_id, customer_id, order_date, status, total)
order_items(order_id, product_id, quantity, unit_price)
products(product_id, name, category, price)
employees(employee_id, name, manager_id, department, salary, hired_on)

The questions

What does ACID mean, in plain terms?

Easy

Atomicity: every write in the transaction happens or none of it does. Consistency: the database moves from one valid state to another, with every constraint still holding at commit. Isolation: concurrent transactions cannot see each other's half-finished work. Durability: once COMMIT returns, the changes survive a crash, because they were written to the log before the commit was acknowledged.

-- accounts(account_id, balance) is not in the shop schema; a transfer needs it.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;    -- or ROLLBACK, which erases both updates

The follow-up is usually "which of the four does the engine own?" Atomicity, isolation and durability are the engine's job, delivered by undo and redo logging plus locking or multi-version storage. Consistency is shared: the engine enforces the constraints you declare, and your code owns the rules the schema cannot express, such as the ledger balancing at the end of the day. Reciting the acronym without splitting it that way is the trap this question sets.

What happens if the connection dies in the middle of a transaction?

Easy

The engine rolls the transaction back. Uncommitted changes were never durable: they lived in memory and in the log only as intent, and crash recovery replays committed work and undoes incomplete work. No other session can commit your transaction for you.

BEGIN;
UPDATE orders SET status = 'processing' WHERE order_id = 42;
UPDATE orders SET status = 'processing' WHERE order_id = 43;
-- connection drops here: both updates are undone, no partial state survives
COMMIT;

Two consequences worth naming: the locks the transaction held are released, so a dead connection cannot block others beyond the cleanup; and anything the application already sent on the side, a confirmation email or a queue message, is not rolled back with the data, which is the gap the transactional outbox pattern exists to close. The trap is designing around "it will probably commit"; the whole point of the transaction is assuming the opposite.

What is autocommit, and when does a transaction start implicitly?

Easy

Autocommit wraps every standalone statement in its own transaction and commits it the moment the statement finishes. It is the default on PostgreSQL, MySQL, SQL Server, Oracle and SQLite. Writing BEGIN (START TRANSACTION or BEGIN TRANSACTION on MySQL and SQL Server) suspends autocommit until the matching COMMIT or ROLLBACK.

-- Each statement commits itself:
UPDATE orders SET status = 'shipped' WHERE order_id = 42;

-- Two statements, one fate:
BEGIN;
UPDATE orders SET status = 'shipped' WHERE order_id = 42;
UPDATE orders SET status = 'shipped' WHERE order_id = 43;
COMMIT;

The detail that catches people: drivers and ORMs often run with autocommit off and issue BEGIN themselves, so a connection that looks idle can be sitting inside an open transaction holding its locks. The trap answer is "a single UPDATE outside a transaction is not atomic"; one statement is always atomic, autocommit or not. Transactions exist to give many statements the guarantee that one statement already has.

What are the three read anomalies: dirty read, non-repeatable read and phantom?

中

A dirty read sees a row another transaction wrote but has not committed; if that transaction rolls back, you built logic on a value that never existed. A non-repeatable read gets different values for the same row read twice in one transaction, because another transaction updated and committed in between. A phantom runs the same range query twice and the second run returns rows the first did not see, because another transaction inserted and committed in between.

-- Session A reads:
SELECT total FROM orders WHERE order_id = 42;        -- 100
-- Session B updates and commits:
UPDATE orders SET total = 200 WHERE order_id = 42; COMMIT;
-- Session A reads the same row again:
SELECT total FROM orders WHERE order_id = 42;        -- 200: non-repeatable read

-- Session A counts:
SELECT COUNT(*) FROM orders WHERE customer_id = 7;   -- 4
-- Session B inserts one more order for customer 7 and commits.
-- Session A counts again:
SELECT COUNT(*) FROM orders WHERE customer_id = 7;   -- 5: a phantom

The distinction the follow-up probes: a non-repeatable read is one row changing, a phantom is rows joining or leaving a predicate. Saying "no modern engine allows dirty reads" is correct but incomplete until you name the mechanism, readers seeing only committed versions. The one common exception is worth knowing: SQL Server's NOLOCK hint (READ UNCOMMITTED) does allow dirty reads, which is why every NOLOCK in a codebase deserves a conversation.

What are the four isolation levels, and which anomaly does each prevent?

中

READ UNCOMMITTED permits dirty reads. READ COMMITTED prevents dirty reads but allows non-repeatable reads and phantoms. REPEATABLE READ also prevents non-repeatable reads, and the SQL standard still permits phantoms at this level. SERIALIZABLE prevents all three: the outcome must be one that running the transactions one after another could also have produced.

--                     dirty reads   non-repeatable   phantoms
-- READ UNCOMMITTED      allowed        allowed       allowed
-- READ COMMITTED          no           allowed       allowed
-- REPEATABLE READ         no              no         allowed by the standard
-- SERIALIZABLE            no              no            no

The senior caveat is that popular engines exceed their own level: PostgreSQL's REPEATABLE READ is snapshot isolation and blocks phantoms too, failing a conflicting write with a serialization error instead of waiting, and MySQL InnoDB's REPEATABLE READ blocks most phantoms with next-key locks on the index range it scanned. Oracle's SERIALIZABLE is snapshot isolation as well. The trap is reciting the standard's matrix as if it described real engines; the interviewer asking this wants the engine reality.

What isolation level does each engine default to, and how do you change it?

中

PostgreSQL, SQL Server and Oracle default to READ COMMITTED; MySQL InnoDB defaults to REPEATABLE READ. SQLite has no level to set: every transaction is serializable because the whole database is one file with database-level locking, and WAL mode gives readers a consistent snapshot without changing that. READ UNCOMMITTED does nothing on PostgreSQL (it is accepted as an alias for READ COMMITTED) and does not exist on Oracle; multi-version storage means neither engine can produce a dirty read in the first place.

-- SQL Server, MySQL and Oracle share the standard spelling:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

-- PostgreSQL makes the level a property of the transaction:
BEGIN ISOLATION LEVEL SERIALIZABLE;
-- or the server default: SET default_transaction_isolation = 'repeatable read';

-- SQLite: nothing to set. Writers take turns on the whole
-- database file; there are no row or table locks to tune.

The nuance that earns credit on SQL Server: its READ COMMITTED can run on row versioning instead of locking, switched on per database with READ_COMMITTED_SNAPSHOT or the SNAPSHOT isolation level, both opt-in. The trap is presenting SQLite's serializability as a feature to celebrate; the honest framing is that with database-level locking there is nothing to isolate from, and write concurrency is bounded by taking turns.

How does MVCC differ from locking?

中

Locking makes readers and writers queue: a writer holds a lock on the rows it changed, and a reader either waits or takes a shared lock that blocks writers. MVCC (multi-version concurrency control) keeps the previous version of a row while a writer builds a new one, so readers read the last committed version without blocking and writers never wait on readers. Writers still conflict with writers; MVCC removes only the reader-writer queue.

-- PostgreSQL: the UPDATE writes a new row version; the old version
-- stays readable and VACUUM reclaims it once nothing needs it.
UPDATE products SET price = 20 WHERE product_id = 7;

-- SQL Server: same idea, opt-in per database, version store in tempdb:
ALTER DATABASE shop SET READ_COMMITTED_SNAPSHOT ON;

Per engine: PostgreSQL and Oracle are multi-version from the ground up (Oracle's cost is undo space, and an exhausted undo tablespace produces the "snapshot too old" error); MySQL InnoDB is multi-version with row locks on top; SQL Server is lock-first with versioning as an opt-in; SQLite is locking only, one writer at a time on the whole file. The trap is saying "MVCC means no locks"; every MVCC engine still locks writes, and two transactions updating the same row still take turns.

What does SELECT FOR UPDATE do, and when is optimistic concurrency the better choice?

中

SELECT FOR UPDATE reads rows and holds a write lock on them until the transaction ends, so another transaction's FOR UPDATE or UPDATE on those rows waits. It is pessimistic: lock first, then decide. Optimistic concurrency takes no lock; the transaction re-checks what it read at write time and fails cleanly when someone got there first.

-- Pessimistic: the row cannot change under you
BEGIN;
SELECT stock FROM products WHERE product_id = 7 FOR UPDATE;
UPDATE products SET stock = stock - 1 WHERE product_id = 7;
COMMIT;

-- Optimistic: no lock held, verify at write time
UPDATE products SET stock = stock - 1
WHERE product_id = 7 AND stock = 5;   -- zero rows updated: someone moved it

The decision to state out loud: high contention and a short critical section want FOR UPDATE; low contention and cheap retries want optimistic, which scales better because nothing is held across user think time. SQL Server has no FOR UPDATE; its spelling is the UPDLOCK hint. The follow-up is usually what happens when the application never commits: the lock lives until the transaction ends, so a FOR UPDATE taken before a slow API call makes every other buyer queue, and that failure mode is why optimistic wins in web request paths.

What goes wrong when a transaction stays open too long?

中

Everything the transaction holds, it holds for the duration: its locks and its snapshot. Under MVCC the snapshot is what hurts, because old row versions cannot be reclaimed while any transaction might still need them: dead tuples pile up on PostgreSQL until VACUUM can pass, and InnoDB's history list grows until purge catches up. The worst case is idle in transaction, a session that opened a transaction and walked away, holding its snapshot and its locks while doing no work.

-- Find sessions parked inside a transaction (PostgreSQL):
SELECT pid, state, now() - xact_start AS tx_age, left(query, 60) AS query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY tx_age DESC;

-- The guardrail: a timeout for idle transactions
SET idle_in_transaction_session_timeout = '5min';

Name the damage per engine: PostgreSQL table and index bloat with VACUUM falling behind, InnoDB history-list growth slowing every consistent read, SQL Server tempdb version store growth under versioned isolation, and on SQL Server and InnoDB the log cannot truncate past the oldest open transaction. The trap is blaming long queries; a query at least does work, while a forgotten transaction, usually an error path that skipped its rollback, holds everything indefinitely. That is why the timeout and monitoring question comes next.

What is a SAVEPOINT, and when would you roll back to one?

中

A savepoint marks a position inside the current transaction so part of it can be undone without discarding the rest. ROLLBACK TO undoes everything since the named savepoint and keeps the transaction open; RELEASE SAVEPOINT keeps the work and drops the marker.

-- The standard frame: a batch import where one bad row
-- should not kill the whole file
BEGIN;
SAVEPOINT row_10;
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (42, 7, -3);         -- CHECK (quantity > 0) fails here
ROLLBACK TO row_10;         -- the bad row is gone, the transaction lives
INSERT INTO order_items (order_id, product_id, quantity)
VALUES (42, 9, 1);          -- the next row imports normally
COMMIT;                     -- every good row is committed

Every engine here supports the syntax: PostgreSQL, MySQL InnoDB, SQL Server, Oracle and SQLite. Savepoint names are unique within the transaction and roll back in stack order, so rolling back to an early savepoint discards the later ones. The trap is reaching for nested transactions instead: SQL Server's BEGIN inside a transaction only increments @@TRANCOUNT and MySQL treats it the same way, so the outer COMMIT commits everything; the savepoint is the actual partial-rollback tool.

What causes a deadlock, and how does each engine detect and resolve one?

Hard

A deadlock is two transactions each holding a lock the other needs, so both wait forever: A locks row 42 and asks for row 43, B locks row 43 and asks for row 42. No amount of waiting fixes the geometry, so the engine must find the cycle and kill one transaction.

-- The classic: the same rows updated in opposite orders
-- Session A: BEGIN; UPDATE orders ... WHERE order_id = 42; then ... 43;
-- Session B: BEGIN; UPDATE orders ... WHERE order_id = 43; then ... 42;

-- Who dies, and what the error looks like:
-- PostgreSQL:  ERROR:  deadlock detected (after deadlock_timeout, 1s default)
-- MySQL:       error 1213, InnoDB rolls back the smaller transaction
-- SQL Server:  error 1205, victim chosen by cost unless DEADLOCK_PRIORITY says otherwise
-- Oracle:      ORA-00060, and the failing transaction writes a trace file
-- SQLite:      no row locks, so no cycle; the second writer gets SQLITE_BUSY

Diagnosis is the follow-up to have ready: InnoDB prints the last one under LATEST DETECTED DEADLOCK in SHOW ENGINE INNODB STATUS, SQL Server records deadlock graphs in the system_health session, and PostgreSQL logs both statements to the server log when the detector fires. The answers that land: keep a consistent lock order everywhere (update rows in sorted key order), keep transactions short, and retry the victim, because a deadlock is not an engine bug but a property of the locking pattern.

How do you compute peak concurrent sessions from a session log?

Hard

Overlapping intervals, solved with the same running-total pass as gaps and islands: a session start contributes +1, an end contributes -1, sort the events by time and accumulate.

-- PostgreSQL syntax; sessions(session_id, started_at, ended_at)
-- is not in the shop schema:
WITH events AS (
SELECT started_at AS ts, 1 AS delta FROM sessions
UNION ALL
SELECT ended_at, -1 FROM sessions
),
ordered AS (
SELECT ts, SUM(delta) OVER (ORDER BY ts, delta) AS live
FROM events
)
SELECT ts, live FROM ordered ORDER BY live DESC LIMIT 1;

Worked through: sessions from 09:00 to 10:00, 09:30 to 09:45 and 09:40 to 10:30 give sorted deltas +1, +1, +1, -1, -1, -1, and the running total peaks at 3 between 09:40 and 09:45. The ORDER BY ts, delta matters: when an end and a start share an instant, the end must subtract first or the peak overcounts, and surfacing that boundary rule yourself is what the interviewer is really asking. The tie-in to say out loud: run this over your transaction table before tuning isolation levels or locks, because knowing how many transactions actually overlap tells you whether concurrency is even your problem.

Transactions & concurrency interview FAQ

Which engines do the transaction answers cover?

PostgreSQL, MySQL InnoDB, SQL Server, Oracle and SQLite, and the value is mostly in where they disagree: default isolation levels, locking versus MVCC, how each engine picks its deadlock victim, and the different spellings for setting an isolation level.

What schema do these answers use?

The same shop schema as every topic, printed at the top of the page. Concurrency needs rows that two transactions can fight over, so the transfer examples introduce an accounts table and the peak-concurrency question introduces a sessions log, each declared in a comment where it appears.

Is there a question about deadlocks?

A hard one: what causes the cycle, which transaction each engine kills, how PostgreSQL, MySQL, SQL Server, Oracle and SQLite differ on detection, and how to read each engine's own deadlock report.

What is the hardest question here?

Two of them: deadlock diagnosis per engine, and computing peak concurrent sessions from a session log with window functions, which is the gaps-and-islands pattern applied to overlapping intervals. Both are senior-level follow-ups.

Other topics

// from study notes to daily tool

Now write some SQL against a real database

SQLly is a native SQL workbench for macOS, Windows and Linux: IntelliSense that knows your schema, a formatter, guardrails for risky queries, and every engine in one app.

このページのテキストとデータ: CC BY 4.0、出典は SQLly (sqlly.app) と明記してください。 コードと SQL スニペット: MIT. ライセンスの詳細