Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 143/ 160
08. Transactions, Security & Production SQL Administration

Concurrency Anomalies (Dirty Reads, Non-Repeatable Reads, Phantom Reads, Lost Updates)

Recognize classic concurrency anomalies and which isolation levels prevent them.

IntermediateDirty Read · Non-Repeatable3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

When two people change the same data at once, they can see half-finished work, miss each other's changes, or both break a rule without knowing.

Think of it like…

Two cashiers sharing one stock register: each reads "1 left", each sells it, and each writes "0 left". The register looks fine, but two items were sold that didn't exist. That's a lost update.

Where you’ve seen it

Two doctors are on call; the rule is that at least one must remain. Each opens the app, sees two on call, and signs off. Each transaction updated only its own row, so nothing conflicted, but now nobody is on call. That's write skew, prevented only by Serializable isolation or explicit locking.

Words you’ll hear

Dirty read
Reading another transaction's uncommitted change.
Non-repeatable read / phantom
A row's value changes / new rows appear between two reads in one transaction.
Lost update
Two read-then-write transactions; the second overwrites the first's change.
Write skew
Two transactions read the same data, update different rows, and break an invariant together.

Visual diagram

Loading interactive diagram

Theory & example queries

The anomalies and which level stops them

Read Committed (the default in PostgreSQL, SQL Server and Oracle) prevents dirty reads only. Repeatable Read prevents non-repeatable reads, and in PostgreSQL also phantoms. PostgreSQL's Repeatable Read also detects lost updates on the same row and aborts one transaction with a serialization error; MySQL InnoDB's Repeatable Read doesn't, so read-modify-write races still need locks there.

Write skew touches different rows, so row-level conflict detection doesn't notice it. Only Serializable isolation (or explicitly locking the rows you read) prevents it. PostgreSQL's Serializable uses snapshot isolation plus conflict tracking and aborts one of the transactions, which your code must retry.

Write skew with on-call doctorsQuery example
1Input dataStart from the source rows or state that the statement sees.
doctors
3 rows
doctors sample rows
idnameon_call
1Dr. Shahtrue
2Dr. Mehtatrue
3Dr. Raofalse
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  COUNT(*)3FROM4  doctors5WHERE6  on_call
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/6
query.sql
1UPDATE doctors2SET3  on_call = FALSE4WHERE5  id = me
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/5
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
ERROR: could not serialize access due to concurrent update Retry result: 1 doctor remains on call

Note: Representative PostgreSQL error; which transaction is chosen as the serialization victim is engine-dependent.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Each transaction runs

(sees 2) and then

. Under Serializable, one of them fails with a serialization error and retries, then sees only one doctor on call.

Key takeaway: Know which anomaly each isolation level prevents in your database.

Practical fixes

For lost updates, the simplest fix is to make the read-modify-write a single atomic statement: UPDATE products SET stock = stock - 1 WHERE id = 7 AND stock > 0, then check the row count. When logic runs in between, lock first with SELECT … FOR UPDATE, or use optimistic concurrency: keep a version column and update with WHERE id = ? AND version = ?, treating 0 rows updated as "someone else changed it, retry".

For invariants across rows (on-call coverage, no overlapping bookings), use Serializable with retries, lock the relevant rows or a parent row, or move the rule into a constraint the database enforces (an exclusion or unique constraint). Pick the lightest tool that covers the anomaly you actually have.

Optimistic locking with a version columnQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1UPDATE documents2SET3  body = $1,4  version = version + 15WHERE6  id = $27  AND version = $3;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/7
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
UPDATE 0

Note: Representative stale-version case: the row exists, but its current version no longer equals $3.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

If it updates 0 rows, another user saved first: reload and retry, or show a conflict.

Key takeaway: Atomic update, lock, version check or Serializable: match the fix to the anomaly.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Analysis

Draw the two transactions

Write both transactions' reads and writes on a timeline and find where they interleave badly.

Focus at this step

T1 read → T2 read → T1 write → T2 write

What to watch at this step
Tool
a timeline
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

When transactions run at the same time, five classic anomalies can occur. A dirty read sees uncommitted data. A non-repeatable read sees a row change between two reads. A phantom read sees new rows appear in a repeated range query. A lost update happens when two read-modify-write transactions overwrite each other. Write skew happens when two transactions each check a rule, then update different rows, and together break it.

Why it matters: These anomalies cause oversold stock, wrong balances and broken business rules, often only under real traffic. Naming the anomaly is the first step to choosing the fix (an atomic update, a row lock, optimistic versioning or a stricter isolation level), which is why interviewers ask about them.

When to reach for it

  • Inventory, booking and balance updates
  • Collaborative editing (version checks)
  • Business rules spanning several rows

When to avoid or be careful

  • SELECT then UPDATE with a value computed in the application
  • Assuming Repeatable Read prevents write skew
  • Retry-less Serializable

Fixes for concurrency anomalies

Atomic UPDATE with a condition
Best for: Counters, stock, balances

Strengths: No explicit lock; one statement.

Watch out: Only works when the rule fits in the WHERE clause.

Row locks or optimistic versioning
Best for: Read-modify-write with application logic in between

Strengths: Prevents lost updates precisely.

Watch out: Locks block others; version checks need retry handling.

Serializable isolation
Best for: Rules spanning several rows (write skew)

Strengths: Prevents every anomaly.

Watch out: Serialization failures to retry; more overhead.

Interview signals & numbers to know

When this topic comes up

  • “We oversold an item”
  • “Two users edited the same document”
  • “What is a phantom read / write skew?”
  • Race conditions
  • Isolation levels

Benchmarks & rules of thumb

5 -
classic anomalies
Read Committed -
prevents dirty reads only
Serializable -
the only level that prevents write skew

Common mistakes & follow-ups

Common interview mistakes

  • Reading stock in the app, subtracting, and writing the new number back without a lock.
  • Believing that because both transactions updated different rows, they couldn't have conflicted.
  • Ignoring the affected row count of an optimistic UPDATE, so lost conflicts go unnoticed.

Likely interviewer follow-ups

  • What's the difference between a lost update and write skew?
  • How does optimistic locking work?
  • Which isolation level prevents phantom reads in PostgreSQL vs MySQL?
Interview tip: Explain the lost update with the stock example and its atomic-UPDATE fix, then contrast it with write skew (on-call doctors). Covering both shows real depth.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Concurrency Anomalies (Dirty Reads, Non-Repeatable Reads, Phantom Reads, Lost Updates) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
ACID Properties Deep Dive (Atomicity, Consistency, Isolation, Durability)
Next topic
Transaction Isolation Levels (Read Uncommitted, Read Committed, Repeatable Read, Serializable)