Thuta Learning
SQL
AdvancedData & DatabasesBeginner

Transactions & Isolation

SQLLesson 2535 min

What you'll walk away with

  • Run a multi-step change such as a transfer with BEGIN ... COMMIT so it never half-completes
  • Understand that one failing statement aborts the whole PostgreSQL transaction, and undo part of the work with SAVEPOINT
  • Explain what READ COMMITTED, REPEATABLE READ and SERIALIZABLE let a transaction see, including why READ UNCOMMITTED behaves as READ COMMITTED
  • Avoid lost updates and know to retry a transaction that fails with a serialization error (40001)

Explain it simply

Transactions in plain language

A transaction is a bundle of statements. When it reaches COMMIT, every change in the bundle takes effect at once; on ROLLBACK or an error, it is as if nothing happened. Nobody else ever sees the half-finished state.

Think of withdrawing cash at an ATM. Debiting the account and handing out the notes must both happen, or neither. If the account is debited and the machine jams before the cash comes out, the bank must undo the debit.

Problem → Why → Solution

The problem: a half-finished transfer

The wallet app moves 100 from Aye to Bo by running two UPDATE statements one after the other. Without a transaction, each statement commits on its own the moment it finishes (autocommit). If the app server restarts for a deploy right after the first UPDATE, Aye loses 100 and Bo never receives it.

The total in the system drops from 700 to 600, and no log shows an error.

transfer-no-transaction.sql
-- autocommit: each statement is permanent as soon as it finishes
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- the app server restarts here...
UPDATE accounts SET balance = balance + 100 WHERE id = 2;  -- never runs

Why this happens

The database sees two separate pieces of work and has no idea they belong together. BEGIN and COMMIT tell it where that boundary is. If the connection drops before COMMIT, PostgreSQL rolls the transaction back automatically, so the first UPDATE vanishes too and the money stays where it was.

Core concept: all-or-nothing and ACID

Transactions give four guarantees known as ACID. You do not need to memorise them all at once, but knowing which problem each one solves makes it clear why transactions matter.

LetterGuarantee
Atomicityall of the changes happen, or none do
Consistencyevery constraint holds when it commits
Isolationhow much concurrent transactions see of each other
Durabilityafter COMMIT, a crash cannot undo it

In PostgreSQL, BEGIN (or START TRANSACTION) opens a transaction, COMMIT makes it permanent and ROLLBACK discards it. Your own session sees its changes immediately, but other sessions do not see them until COMMIT. An open transaction keeps locks on the rows it has updated, so transactions should be short: never hold one open while waiting for a user to click OK.

PostgreSQL has one special rule: as soon as one statement inside a transaction fails, the whole transaction is aborted, and every later statement is refused with current transaction is aborted. Typing COMMIT at that point performs a ROLLBACK instead. Some databases, such as MySQL, discard only the failed statement and let the transaction continue. To undo just part of the work in PostgreSQL, mark a point with SAVEPOINT name and return to it with ROLLBACK TO SAVEPOINT name.

Atomicity solves the problem of a single transaction, but isolation matters once many users write at the same time. If two transactions read and modify the same row at once, when should one see the other's change? The isolation level answers that question. The higher the level, the fewer anomalies, but the more often PostgreSQL stops a conflicting transaction with an error and asks you to retry it.

The life of a transaction
  1. BEGIN opens a private workspace
  2. Statements run; only you see them
  3. An error aborts it: ROLLBACK only
  4. COMMIT shows everything at once

The isolation level decides when other sessions' commits become visible inside your transaction.

General pattern

sql
BEGIN [ISOLATION LEVEL level];
    statement;
    SAVEPOINT savepoint_name;
    statement;
    ROLLBACK TO SAVEPOINT savepoint_name;  -- undo back to the mark
    statement;
COMMIT;  -- or ROLLBACK; to discard everything

-- level: READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE

The isolation level can go on BEGIN, or be set with SET TRANSACTION ISOLATION LEVEL ... as the first statement after BEGIN. It cannot be changed once a query has run.

Worked example: a transfer inside a transaction

There are two accounts: Aye has 500 and Bo has 200. Putting both UPDATE statements between BEGIN and COMMIT makes them take effect together. The final SELECT shows that the total of 700 is unchanged.

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

SELECT id, owner, balance FROM accounts ORDER BY id;

Code breakdown

  1. Open the unitBEGIN;

    Suspends autocommit and gathers the following statements into one transaction.

  2. DebitUPDATE accounts SET balance = balance - 100 WHERE id = 1;

    balance = balance - 100 computes from the current value inside the database, so concurrent updates are not lost. The row stays locked until COMMIT.

  3. CreditUPDATE accounts SET balance = balance + 100 WHERE id = 2;

    If this statement failed, for example on a CHECK, the transaction would be aborted and the first UPDATE rolled back too.

  4. Make it permanentCOMMIT;

    Writes both changes durably and makes them visible to other sessions at the same instant.

You should see
id | owner | balance
---+-------+--------
 1 | Aye   |  400.00
 2 | Bo    |  300.00

SAVEPOINT: undoing part of a transaction

The transaction below takes 50 from Aye and sets a savepoint. It then credits Bo with 999 by mistake, undoes only that with ROLLBACK TO SAVEPOINT, and credits the correct 50. The first UPDATE survives, so the result is Aye 450.00 and Bo 250.00. Application drivers use the same trick to wrap a step that might fail, so one error does not ruin the whole transaction.

savepoint.sql
BEGIN;
UPDATE accounts SET balance = balance - 50 WHERE id = 1;
SAVEPOINT before_credit;

UPDATE accounts SET balance = balance + 999 WHERE id = 2;  -- wrong amount
ROLLBACK TO SAVEPOINT before_credit;                      -- undo only that

UPDATE accounts SET balance = balance + 50 WHERE id = 2;
COMMIT;

SELECT id, owner, balance FROM accounts ORDER BY id;

PostgreSQL's four isolation levels

The SQL standard defines four isolation levels and PostgreSQL accepts all four as syntax. Because PostgreSQL uses MVCC, keeping several versions of each row, it never shows uncommitted data: choosing READ UNCOMMITTED gives exactly READ COMMITTED behaviour. The default is READ COMMITTED.

LevelSnapshotStill possible in PostgreSQL
READ UNCOMMITTEDsame as READ COMMITTEDno dirty reads; otherwise as READ COMMITTED
READ COMMITTED (default)a new one per statementnon-repeatable reads, phantoms, lost updates
REPEATABLE READone for the whole transactionno phantoms; write skew is possible
SERIALIZABLEas if run one at a timeno anomalies; may fail with 40001

A single-connection database such as PGlite cannot run two sessions at once, so follow the timeline below yourself in two psql windows. Under READ COMMITTED, every statement in session A takes a fresh snapshot, so step 6 sees B's commit. Under REPEATABLE READ, step 6 would still see 500.

text
Non-repeatable read under READ COMMITTED
----------------------------------------
step  Session A                          Session B
----  ---------------------------------  ---------------------------------
 1    BEGIN;
 2    SELECT balance FROM accounts
        WHERE id = 1;          -- 500
 3                                       BEGIN;
 4                                       UPDATE accounts
                                           SET balance = balance - 100
                                           WHERE id = 1;
 5                                       COMMIT;
 6    SELECT balance FROM accounts
        WHERE id = 1;          -- 400
 7    COMMIT;

A lost update is more dangerous: A reads 500, computes 450 in the app and writes SET balance = 450, wiping out the 100 that B subtracted. There are three fixes: let the database do the arithmetic with SET balance = balance - 50, lock the row first with SELECT ... FOR UPDATE, or use REPEATABLE READ or SERIALIZABLE. With the last option PostgreSQL fails one transaction with could not serialize access (SQLSTATE 40001), and the app must retry the whole transaction from the start.

In real projects

Transactions in real projects

Web apps usually open transactions through a driver or ORM helper rather than typing BEGIN: Django's transaction.atomic(), Prisma's $transaction, or BEGIN/COMMIT on a single checked-out client in node-postgres. The helpers issue ROLLBACK automatically when an exception escapes. With a connection pool, BEGIN and COMMIT must run on the same connection; taking each query from the pool separately can scatter the statements across different connections.

  • Booking systems stop two people from taking the same seat with SELECT ... FOR UPDATE, or with SERIALIZABLE plus a retry loop.
  • Reporting jobs run many queries inside one REPEATABLE READ READ ONLY transaction so every table is read from the same snapshot in time.
  • Monitoring watches for sessions that are idle in transaction, because they hold locks and hold back vacuum; the idle_in_transaction_session_timeout setting can end them automatically.

Common mistakes

Common transaction mistakes

Read, compute in the app, write back

Selecting the balance, computing a new value in the app and writing SET balance = 450 erases a concurrent update under READ COMMITTED. Use a relative update such as SET balance = balance - 50, or lock the row first with FOR UPDATE.

Carrying on after an error inside the transaction

After an error in PostgreSQL, every statement fails with current transaction is aborted, and COMMIT just rolls back. Driver code must catch the error and send ROLLBACK, or use a savepoint if it wants to continue.

Not retrying serialization failures

Choosing REPEATABLE READ or SERIALIZABLE means agreeing to receive an error on conflict. Passing 40001 to the user as a 500 makes the feature fail at random; retry the whole transaction a limited number of times instead.

Mini challenge

Mini challenge: a guarded transfer

There is an accounts table (Aye 500, Bo 200) and a transfers log. Write a transaction that moves money only when the sender can afford it and records the transfer in the log. Moving 30 must succeed, and trying to move 1000 must change nothing.

  • Put each transfer inside BEGIN ... COMMIT
  • Debit only when balance >= amount, and credit and log only if the debit happened
  • Transfer 30 from Aye to Bo, then attempt to transfer 1000
  • Show the final balances and the number of transfer rows
guarded-transfer.sql
BEGIN;
-- TODO: debit account 1 by 30, but only if it has at least 30
--       (return the id of the row you changed)
-- TODO: credit account 2 by 30 only if the debit returned a row
-- TODO: insert (1, 2, 30) into transfers only if the credit happened
COMMIT;

BEGIN;
-- TODO: the same three steps for 1000; nothing should change
COMMIT;

-- TODO: show both balances and how many transfers were logged

Expected: Aye has 470.00, Bo has 230.00 and transfers holds exactly one row. The 1000 transfer changes zero rows and raises no error.

Show hint

Use a data-modifying CTE such as WITH debit AS (UPDATE ... WHERE id = 1 AND balance >= 30 RETURNING id). Chain the later steps to it with EXISTS (SELECT 1 FROM debit) or SELECT ... FROM credit. Because it is one statement, a failure in any part rolls back all of it.

Show solution
guarded-transfer.sql
BEGIN;
WITH debit AS (
    UPDATE accounts SET balance = balance - 30
    WHERE id = 1 AND balance >= 30
    RETURNING id
), credit AS (
    UPDATE accounts SET balance = balance + 30
    WHERE id = 2 AND EXISTS (SELECT 1 FROM debit)
    RETURNING id
)
INSERT INTO transfers (from_id, to_id, amount)
SELECT 1, 2, 30 FROM credit;
COMMIT;

BEGIN;
WITH debit AS (
    UPDATE accounts SET balance = balance - 1000
    WHERE id = 1 AND balance >= 1000
    RETURNING id
), credit AS (
    UPDATE accounts SET balance = balance + 1000
    WHERE id = 2 AND EXISTS (SELECT 1 FROM debit)
    RETURNING id
)
INSERT INTO transfers (from_id, to_id, amount)
SELECT 1, 2, 1000 FROM credit;
COMMIT;

SELECT a.id, a.balance, (SELECT count(*) FROM transfers) AS transfers_logged
FROM accounts AS a
ORDER BY a.id;

Quick quiz 1 / 3

In PostgreSQL you run BEGIN; an UPDATE that succeeds; an INSERT that fails with a duplicate key; another UPDATE; then COMMIT;. What is saved after COMMIT?

Quick quiz 2 / 3

In PostgreSQL, after BEGIN ISOLATION LEVEL READ UNCOMMITTED;, can your SELECT see a row another session has inserted but not yet committed?

Quick quiz 3 / 3

A SERIALIZABLE transaction fails with could not serialize access ... (SQLSTATE 40001). What should the app do?

What to remember

  • BEGIN ... COMMIT turns several statements into one all-or-nothing unit; ROLLBACK discards it.
  • In PostgreSQL one error aborts the whole transaction; use SAVEPOINT to undo only part of the work.
  • READ COMMITTED is the default, READ UNCOMMITTED behaves the same, and dirty reads never happen.
  • REPEATABLE READ and SERIALIZABLE may fail with 40001, so the app must retry the whole transaction.

Transactions Tutorial — PostgreSQL Global Development Group

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.