Skip to the solution
MediumDSA14 min read

What are transaction isolation levels?

924 views

The problem

Question presented to candidate: "What are transaction isolation levels? Name them, tell me which problems each one prevents, and tell me what your database uses by default and why it is not the strictest one."

What a strong answer should cover:

  • Isolation is a dial between correctness and concurrency: the stricter the level, the more the database must block or abort concurrent transactions
  • The three read phenomena the SQL standard uses: dirty read, non-repeatable read, phantom read β€” and the four levels defined by which of them they allow (READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE)
  • Anomalies the standard table misses: lost update and write skew; only SERIALIZABLE rules out all of them
  • Real defaults: PostgreSQL, SQL Server and Oracle use READ COMMITTED, MySQL InnoDB uses REPEATABLE READ, SQLite is serializable; engines may implement a level more strictly than the standard (PostgreSQL treats READ UNCOMMITTED as READ COMMITTED)
  • Implementation: locks versus MVCC snapshots, and how to set the level per transaction

Code / implementation expected: Optional β€” a two-session timeline showing one anomaly, and the syntax to set a level for one transaction.

Schema used by the examples:

  • isolation-levels

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

14 min read Β· 12 sections

Run the code

Edit the query and run it against the tables for this question.

SQLA lost update replayed step by step: two sessions read 5, both write 4
SQLThe same two sales as atomic updates: the database reads and writes in one step
PostgreSQL: set the level for one transaction and read it back
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT current_setting('transaction_isolation')         AS this_transaction,
       current_setting('default_transaction_isolation') AS server_default;
COMMIT;
PostgreSQL: READ UNCOMMITTED is accepted (it behaves as READ COMMITTED)
BEGIN ISOLATION LEVEL READ UNCOMMITTED;
SELECT current_setting('transaction_isolation') AS level_you_asked_for,
       (SELECT balance FROM accounts WHERE id = 1) AS alice_balance;
COMMIT;

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 34 of 82 in SQL

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All SQL questions
Up nextMedium

What are foreign key cascade options?

Continue