appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Transactions and isolation

Lesson 2 of 412 minAdvanced

Keep data consistent when many users write at the same time.

A transaction groups statements so they succeed or fail together. The guarantees are summarised as ACID: atomic, consistent, isolated and durable.

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

If something goes wrong before COMMIT, use ROLLBACK and neither change is kept. Without a transaction, a crash between the two updates would lose money.

Isolation levels

Isolation controls what one transaction can see of the others that run at the same time. Stronger isolation prevents more anomalies but allows less concurrency.

LevelPrevents
Read committedDirty reads (seeing uncommitted data). Default in PostgreSQL and SQL Server
Repeatable readNon-repeatable reads. Default in MySQL InnoDB
SerializableAll anomalies, as if transactions ran one after another

Locks and lost updates

Two transactions that read a value, change it and write it back can overwrite each other. Avoid this by updating in one statement (SET balance = balance - 100) or by locking the row you read with SELECT ... FOR UPDATE.

CarefulKeep transactions short. A transaction that stays open holds locks and blocks other users, and two transactions waiting on each other cause a deadlock, which the database resolves by cancelling one.

NoteExact behaviour at each isolation level differs between engines. Check the documentation of the one you use.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What does the A in ACID (atomicity) guarantee?
2. How can you avoid a lost update on a counter?
HintOne word.

Key terms