Transactions

Topic 4 of 5 in Changing data11 min readBeginnerFree course

Overview

Placing an order isn’t one change — it’s several: create the order, add its items, reduce the stock. If the server crashes or a check fails halfway through, you’d be left with an order without items, or stock reduced for an order that doesn’t exist. Transactions prevent that: they group statements into a single unit that either happens completely or not at all.

BEGIN, COMMIT, ROLLBACK

Transactions: all or nothing. BEGIN starts the transaction; two statements follow, such as UPDATE accounts SET balance = … twice. Then COMMIT saves both changes, or ROLLBACK means neither happened. The four ACID properties: Atomic — all succeed or none do; Consistent — constraints always hold; Isolated — no half-done work is seen by others; Durable — commits survive a crash. Without BEGIN, each statement commits on its own (autocommit); after an error inside a transaction, ROLLBACK. Isolation: by default (READ COMMITTED) each statement sees data committed before it started. Concurrent updates to the same row wait for each other; SELECT … FOR UPDATE locks rows you are about to change.

  • BEGIN starts a transaction.
  • COMMIT makes all its changes permanent and visible to everyone.
  • ROLLBACK throws all its changes away, as if they’d never happened.
SQL
BEGIN;
UPDATE products SET stock = stock - 1 WHERE id = 1;
UPDATE products SET stock = stock + 1 WHERE id = 2;
SELECT id, stock FROM products WHERE id IN (1, 2) ORDER BY id;
COMMIT;
Text
BEGIN
UPDATE 1
UPDATE 1
 id | stock 
----+-------
  1 |    39
  2 |    56
(2 rows)

COMMIT

Inside the transaction you see your own changes immediately; other sessions don’t see them until COMMIT.

ROLLBACK is the undo button. Say you start a price change and realise it’s wrong:

SQL
BEGIN;
UPDATE products SET price = price * 10;          -- oops: no WHERE!
SELECT name, price FROM products WHERE id <= 3 ORDER BY id;
ROLLBACK;
SELECT name, price FROM products WHERE id <= 3 ORDER BY id;
Text
BEGIN
UPDATE 12
         name          | price  
-----------------------+--------
 Ethiopian Yirgacheffe | 145.00
 Colombian Supremo     | 120.00
 Decaf House Blend     | 112.50
(3 rows)

ROLLBACK
         name          | price 
-----------------------+-------
 Ethiopian Yirgacheffe | 14.50
 Colombian Supremo     | 12.00
 Decaf House Blend     | 11.25
(3 rows)

Inside the transaction every price was ten times too high; after ROLLBACK, nothing changed. This is why experienced people run risky changes inside BEGIN … ROLLBACK first, check the result, and only then run them again with COMMIT.

Autocommit

What about all the changes in the previous lessons, which had no BEGIN? By default psql (and most drivers) run in autocommit mode: each statement is its own little transaction, committed as soon as it succeeds. A single UPDATE touching 1,000 rows is still all-or-nothing — if row 600 violates a constraint, none of the rows change. BEGIN is for making several statements behave as one.

Errors abort the transaction

If any statement inside a transaction fails, PostgreSQL marks the whole transaction as failed. Every later statement is refused, and COMMIT turns into a rollback:

SQL
BEGIN;
UPDATE products SET stock = stock + 100 WHERE id = 5;
UPDATE products SET stock = -1 WHERE id = 6;     -- violates CHECK (stock >= 0)
SELECT stock FROM products WHERE id = 5;
COMMIT;
SELECT stock FROM products WHERE id = 5;
Text
BEGIN
UPDATE 1
ERROR:  new row for relation "products" violates check constraint "products_stock_check"
DETAIL:  Failing row contains (6, Jasmine Green, 2, 12.75, -1).
ERROR:  current transaction is aborted, commands ignored until end of transaction block
ROLLBACK
 stock 
-------
    80
(1 row)

The first update looked fine, but because the second failed, the transaction as a whole was rolled back — Assam’s stock is still 80. That’s atomicity doing its job: you can never commit half of a transaction. (Some other databases carry on after an error inside a transaction; PostgreSQL deliberately doesn’t.)

Savepoints

Sometimes you want to recover from an error without losing everything before it. A savepoint marks a point inside a transaction that you can roll back to:

SQL
BEGIN;
INSERT INTO categories (name) VALUES ('Gifts');
SAVEPOINT before_risky;
INSERT INTO categories (name) VALUES ('Tea');      -- duplicate: fails
ROLLBACK TO SAVEPOINT before_risky;
INSERT INTO categories (name) VALUES ('Snacks');
COMMIT;
SELECT id, name FROM categories ORDER BY id;
Text
BEGIN
INSERT 0 1
SAVEPOINT
ERROR:  duplicate key value violates unique constraint "categories_name_key"
DETAIL:  Key (name)=(Tea) already exists.
ROLLBACK
INSERT 0 1
COMMIT
 id |    name     
----+-------------
  1 | Coffee
  2 | Tea
  3 | Equipment
  4 | Accessories
  5 | Gifts
  7 | Snacks
(6 rows)

The failed insert was undone, but Gifts (before the savepoint) and Snacks (after it) were both committed. Application frameworks use savepoints to implement “nested” transactions.

ACID

Transactions give four guarantees, known as ACID:

  • Atomicity — all of a transaction’s changes happen, or none do.
  • Consistency — every constraint holds when the transaction commits; you can’t commit data that breaks the rules.
  • Isolation — transactions running at the same time don’t see each other’s unfinished work.
  • Durability — once COMMIT returns, the data survives a crash or power cut (PostgreSQL writes it to its write-ahead log on disk first).

These guarantees are the main reason businesses keep important data in a relational database.

Concurrency: when two sessions meet

A real shop has many sessions running at once. What happens when two of them change the same row? PostgreSQL locks a row when it’s updated, and a second transaction that wants to update it waits until the first finishes:

Time Session A Session B
1 BEGIN;
2 UPDATE products SET stock = stock - 1 WHERE id = 9; (6 → 5)
3 UPDATE products SET stock = stock - 1 WHERE id = 9; — waits
4 COMMIT;
5 …continues, sees 5, writes 4

Both decrements count, and the stock ends at 4. Because SET stock = stock - 1 is calculated when the row is written, from its current value, concurrent sales can’t overwrite each other. (Sessions that only read never wait: they see the last committed version.)

The lost update — and how to avoid it

Problems appear when an application reads a value, calculates in its own code, and writes the result back:

Time Session A Session B
1 SELECT stock … WHERE id = 9; → 6
2 SELECT stock … WHERE id = 9; → 6
3 UPDATE … SET stock = 5 … (6 − 1)
4 UPDATE … SET stock = 5 … (6 − 1)

Two grinders sold, but the stock only dropped by one: session B overwrote A’s change with a value calculated from stale data. This is the lost update. Three ways to prevent it:

  1. Let the database do the arithmetic: SET stock = stock - 1, as above. Often the simplest fix.
  2. Lock the row when you read it with SELECT … FOR UPDATE inside a transaction. A second session trying to read the same row FOR UPDATE waits until the first commits:
SQL
BEGIN;
SELECT stock FROM products WHERE id = 9 FOR UPDATE;   -- locks the row
-- the application checks there's enough stock, then:
UPDATE products SET stock = stock - 1 WHERE id = 9;
COMMIT;
  1. Guard the write with a condition, so it fails safely if the data changed: UPDATE products SET stock = stock - 1 WHERE id = 9 AND stock >= 1, then check the row count.

You’ll use option 2 in the final project to stop an event being overbooked.

Isolation levels in brief

PostgreSQL’s default isolation level, READ COMMITTED, means each statement sees the data committed before that statement started. It’s a good default for most applications. Stricter levels exist — REPEATABLE READ (the whole transaction sees one snapshot) and SERIALIZABLE (transactions behave as if run one after another, and PostgreSQL aborts any that can’t be) — chosen with BEGIN ISOLATION LEVEL SERIALIZABLE;. With the stricter levels, the application must be ready to retry transactions that fail with a serialization error.

Keep transactions short. A transaction that stays open holds its locks — other sessions wanting those rows wait. Never leave a transaction open while waiting for a user to click something.

Exercise

Place an order safely

Placing an order touches three tables, and it must be all-or-nothing. In one transaction: insert an order for customer 7 placed at 2026-12-04 15:00, status 'paid', shipping fee 5.99 (it will get id 25); insert one item for order 25 — 2 × Pour-Over Dripper (product 8) at 24.00; and reduce the dripper's stock by 2. Commit. Then, after the transaction, select the dripper's name and stock (it should now be 13) and the number of items in order 25.

SQL
BEGIN;

-- 1. the order  2. its item  3. the stock

COMMIT;

Summary

  • A transaction groups statements so that either all of their changes are saved (COMMIT) or none are (ROLLBACK).
  • Without BEGIN, every statement is its own transaction and is committed immediately (autocommit).
  • After an error inside a transaction, PostgreSQL refuses further statements until you ROLLBACK (or roll back to a savepoint).
  • ACID: transactions are Atomic, keep the database Consistent, are Isolated from each other, and Durable once committed.
  • Two transactions changing the same row take turns; to avoid lost updates, change values with SET x = x - 1 or lock rows first with SELECT … FOR UPDATE.