Transactions and isolation levels

A transaction is a group of statements that either all take effect or none do. That part is easy. The hard part — and the interview question — is what your transaction sees while other transactions are running alongside it.

The baseline

BEGIN;
UPDATE employee SET salary = salary * 1.1 WHERE department_id = 1;
UPDATE employee SET salary = salary * 1.05 WHERE department_id = 2;
COMMIT;

Either both raises happen or neither does. A failure between them leaves no half-applied state, and no other transaction ever observes the intermediate.

BEGIN;
DELETE FROM sale;
ROLLBACK;
SELECT count(*) AS still_here FROM sale;

Six. The DELETE happened and then un-happened.

In Postgres, DDL is transactional too. CREATE TABLE, ALTER TABLE and DROP TABLE all roll back, which is why Postgres migrations can be atomic and MySQL migrations historically could not. It is a genuine operational difference worth knowing.

BEGIN;
CREATE TABLE temp_thing (x int);
ROLLBACK;
SELECT * FROM temp_thing;

The table is gone, because the CREATE was inside the rolled-back transaction.

One exception worth knowing: sequences are not transactional. nextval() does not roll back, deliberately — two transactions must never get the same id, so the counter advances even if the work is abandoned. That is why a rolled-back insert leaves a gap in an auto-increment column, which is not a bug and not worth fixing.

ACID, briefly

Reciting the acronym is not the question, but the vocabulary matters:

  • Atomicity — all or nothing. The ROLLBACK above.
  • Consistency — constraints hold at transaction boundaries.
  • Isolation — the subject of the rest of this lesson.
  • Durability — once committed, it survives a crash.

Isolation is the one with a dial on it, and the one that costs performance, so it is the one with interesting trade-offs.

The anomalies, which are what the levels are actually defined by

Learn the anomalies and the levels become obvious rather than memorised.

Dirty read — you see another transaction’s uncommitted data. It might be rolled back a moment later, so you acted on something that never happened.

Non-repeatable read — you read a row twice in one transaction and get different values, because someone else committed an UPDATE in between.

Phantom read — you run the same query twice and the second time there are new rows, because someone else committed an INSERT matching your predicate.

Lost update — two transactions read the same value, both compute a new one from it, and the second write silently overwrites the first. This is the one that actually bites application code, and the one the acronym drills tend to skip.

The four levels

Level Dirty read Non-repeatable read Phantom
Read uncommitted possible possible possible
Read committed no possible possible
Repeatable read no no possible
Serializable no no no

That is the standard. What an engine implements can be stricter:

SHOW transaction_isolation;

Postgres has no read uncommitted — asking for it gives you read committed, because its MVCC design has no way to expose uncommitted rows. And Postgres’s repeatable read also prevents phantoms, because it is implemented as a snapshot taken at the first statement, so the whole transaction sees one consistent view of the database.

So in Postgres there are effectively three levels, and the default is read committed.

What read committed actually means

This is the part people get wrong, and it is a good interview question because the answer is counter-intuitive.

Read committed takes a fresh snapshot per statement, not per transaction. So within one transaction:

BEGIN;
SELECT count(*) FROM employee;
-- another transaction commits an INSERT here
SELECT count(*) FROM employee;   -- a DIFFERENT number
COMMIT;

Both reads are of committed data, so neither is dirty — and they disagree. If your logic depends on two reads agreeing, read committed does not give you that, and the fix is REPEATABLE READ:

BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM employee;
SELECT count(*) FROM employee;   -- guaranteed identical
COMMIT;

The lost update, and the two ways to prevent it

The classic read-modify-write:

T1: SELECT salary FROM employee WHERE id = 1;   -- 120000
T2: SELECT salary FROM employee WHERE id = 1;   -- 120000
T1: UPDATE employee SET salary = 130000 WHERE id = 1;
T2: UPDATE employee SET salary = 125000 WHERE id = 1;   -- T1's raise is gone

Read committed permits this, and so does naive repeatable read in the standard. Three fixes, in increasing order of cost:

Do the arithmetic in the database. The cheapest fix and the one most often missed — there is no read-modify-write to lose:

UPDATE employee SET salary = salary + 10000 WHERE id = 1;

Lock the row when you read it, which is pessimistic concurrency:

BEGIN;
SELECT salary FROM employee WHERE id = 1 FOR UPDATE;
UPDATE employee SET salary = 130000 WHERE id = 1;
COMMIT;

FOR UPDATE makes any other transaction trying to lock that row wait. Correct, and it serialises access to the row — the subject of locking and deadlocks.

Detect the conflict instead of preventing it, which is optimistic concurrency: carry a version column and make the update conditional on it. Nobody waits; a loser retries.

UPDATE employee SET salary = 130000 WHERE id = 1 AND salary = 120000;

Zero rows updated means someone else got there first. Better suited to low contention, where waiting would cost more than the occasional retry.

Serializable, and why it is not the default

SERIALIZABLE guarantees the result is as if the transactions ran one after another. In Postgres this is Serializable Snapshot Isolation, which does not lock — it watches for dependency cycles and aborts one transaction with a serialization failure.

That changes the contract for the application: any transaction can fail and must be retried. Code that assumes a committed transaction succeeded is wrong under serializable. That is the real cost, more than the throughput.

Use it when correctness across multiple rows genuinely requires it — booking the last seat, enforcing a balance that must never go negative — and write the retry loop.

Try it

The single-statement arithmetic versus read-modify-write pair is the one to internalise. The SQL playground runs one connection, so it cannot demonstrate two transactions interfering — which is worth knowing as a limit of the tool rather than a limit of the idea.

Drill it with Adjust salaries atomically and Merge a batch into a daily counter, whose read-then-write alternative no isolation level below SERIALIZABLE makes safe.

Isolation is also a system-design lever; the HLD fundamentals cover consistency across services, and SQL vs NoSQL covers stores that offer weaker guarantees by design.

Interview questions

1. What are the four isolation levels, and which does Postgres default to? Read uncommitted, read committed, repeatable read, serializable. Postgres defaults to read committed and does not implement read uncommitted at all.

2. What is a non-repeatable read, and which level prevents it? Reading the same row twice in one transaction and getting different values because another transaction committed in between. Repeatable read prevents it.

3. Does read committed give you a consistent view of the database? No. It takes a fresh snapshot per statement, so two reads in one transaction can disagree. Only repeatable read and above give one snapshot for the whole transaction.

4. What is a lost update, and how do you prevent it? Two transactions read a value, both derive a new one, and the second write overwrites the first. Prevent it by doing the arithmetic in a single statement, by locking with SELECT ... FOR UPDATE, or by an optimistic version check that updates zero rows on conflict.

5. Why is serializable not the default? Because in Postgres it detects conflicts and aborts transactions, so every transaction becomes retryable and the application must handle serialization failures. That is a contract change, not just a throughput cost.

6. Is DDL transactional? In Postgres, yes — CREATE, ALTER and DROP all roll back, which is what makes atomic migrations possible. Sequences are the notable exception: nextval() does not roll back, so a rolled-back insert leaves an id gap.

Next

Locking and deadlocks — what FOR UPDATE actually does, and how two transactions wedge each other.