Skip to content
Engineering Bible
SQL and Databases

SQL and Databases on transactions

A transaction is all or nothing

  • BEGIN starts one. COMMIT saves every change. ROLLBACK undoes them all.
  • Moving money takes two UPDATEs. A crash between them must not lose the money.
  • Without BEGIN, each statement is its own transaction.
BEGIN;
UPDATE accounts SET balance = balance - 100
  WHERE id = 1;
UPDATE accounts SET balance = balance + 100
  WHERE id = 2;
COMMIT;
Both updates happen or neither does. Other sessions never see the money missing.

ACID is the promise a transaction makes

  • Atomic: all of its changes happen, or none do.
  • Consistent: every constraint holds at commit, or the transaction is rolled back.
  • Isolated: nobody else sees its changes before it commits.
  • Durable: once committed, the changes survive a crash.

Readers and writers do not block each other

  • PostgreSQL keeps old versions of rows, so each query reads a fixed snapshot.
  • Reading never blocks writing, and writing never blocks reading.
  • Two writers to the same row do queue. The second waits for the first to finish.

Concurrent transactions can surprise each other

  • Nonrepeatable read: you read a row twice and it changed in between.
  • Phantom read: you run a query twice and new rows match the second time.
  • Serialization anomaly: the result fits no one-at-a-time order of the transactions.

The isolation level picks which surprises can happen

  • PostgreSQL defaults to Read Committed: each statement sees data committed before it began.
  • Repeatable Read gives the whole transaction one snapshot.
  • MySQL's InnoDB defaults to Repeatable Read, so the same code can behave differently.
PostgreSQL levelNonrepeatable readPhantom readSerialization anomaly
Read Committed (default)PossiblePossiblePossible
Repeatable ReadPreventedPreventedPossible
SerializablePreventedPreventedPrevented
PostgreSQL never shows uncommitted data. Its Read Uncommitted behaves like Read Committed.

Read, then write, is a race

  • Two requests read balance = 100. Each writes 100 - 80 = 20. 160 was spent from 100.
  • Fix one: do the math in SQL. SET balance = balance - 80 WHERE balance >= 80.
  • Fix two: SELECT ... FOR UPDATE locks the row until your transaction ends.

Keep transactions short and ready to retry

  • Locks last until the transaction ends. Never wait for a person while one is open.
  • A deadlock is two transactions each waiting for the other. PostgreSQL aborts one.
  • Avoid deadlocks by locking rows in the same order everywhere.
  • Repeatable Read and Serializable fail on conflict with error 40001. Rerun from the start.
SQL and Databases in seven pages5 / 7