Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PG
PostgreSQL
0/11 completed
Beginner
Why PostgreSQL?psql and your first tablesData types that matter
Intermediate
Constraints and relationshipsPostgres-powered SQLJSONB, arrays and full-text search
Advanced
Views, functions and triggersIndexes and EXPLAINTransactions, MVCC and locking
Pro
Roles, privileges and row-level securityBackups, replication and production
Tracks / PostgreSQL / Advanced

Transactions, MVCC and locking

Real apps have many users changing data at the same time. Two people buy the last ticket; a transfer debits one account but crashes before crediting the other. Transactions are how PostgreSQL keeps data correct in that chaos.

ACID in one table

Letter Promise
Atomic All statements in a transaction happen, or none do
Consistent Constraints hold before and after
Isolated Concurrent transactions don't see each other's half-finished work
Durable Once committed, it survives a crash (it's in the write-ahead log on disk)

BEGIN, COMMIT, ROLLBACK

Every statement runs in a transaction. Normally each one is its own ("autocommit"). BEGIN groups several:

⚙️ Setup: this runs automatically in every editor below
sql
CREATE TABLE accounts (
  id      integer PRIMARY KEY,
  owner   text NOT NULL,
  balance numeric(12,2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Rahul', 100);
PostgreSQL · editable

ROLLBACK throws all the changes away:

PostgreSQL · editable

Errors abort the whole transaction

If any statement fails, Postgres refuses to run anything else in that transaction until you roll back. This protects you from committing half a change:

PostgreSQL · editable

Notice the COMMIT reports ROLLBACK: nothing from the failed transaction was saved.

Savepoints: partial rollback

A savepoint is a checkpoint inside a transaction that you can roll back to:

PostgreSQL · editable

MVCC: how Postgres handles concurrency

PostgreSQL uses Multi-Version Concurrency Control. An UPDATE doesn't overwrite a row in place: it writes a new version and marks the old one as expired. Each transaction sees the versions that were committed when it started (or when its statement started). The result:

  • Readers never block writers, and writers never block readers.
  • Only two writers changing the same row wait for each other.

You can peek at the hidden system columns: xmin is the transaction that created the row version, and ctid is its physical location:

PostgreSQL · editable

Asha's row moved to a new ctid with a new xmin: it's a new version. The old one is now a dead tuple. VACUUM (run automatically by autovacuum) cleans dead tuples up so the space can be reused. If autovacuum can't keep up on a busy table, the table bloats, so it's worth monitoring.

Isolation levels

How much do concurrent transactions see of each other? SQL defines isolation levels:

Level Each statement sees… Prevents Default?
Read Committed Everything committed before the statement started Dirty reads ✅ Postgres default
Repeatable Read A snapshot from the transaction's first query + non-repeatable reads, phantoms
Serializable As if transactions ran one at a time + all anomalies (may abort with a serialization error)
sql
BEGIN ISOLATION LEVEL REPEATABLE READ;
-- ...
COMMIT;

With Repeatable Read and Serializable, Postgres may abort a transaction with could not serialize access. Your app must then retry it. That's normal, not a bug.

The lost-update problem

Two requests run this at the same time, in two sessions (the editor has a single session, so here's the timeline):

Session A                               Session B
SELECT stock FROM products WHERE id=10;  
  → 1                                   SELECT stock FROM products WHERE id=10;
                                          → 1
UPDATE products SET stock = 0 …;        UPDATE products SET stock = 0 …;
-- both think they sold the last monitor! One sale is lost.

Fix 1: do the maths in SQL, so the check and the change are one atomic statement:

PostgreSQL · editable

Fix 2: lock the row with SELECT … FOR UPDATE. A second session's FOR UPDATE on the same row waits until the first commits:

PostgreSQL · editable

A job queue with SKIP LOCKED

FOR UPDATE SKIP LOCKED lets many workers pull jobs from one table without ever grabbing the same job. Each worker skips rows another worker has locked:

PostgreSQL · editable

Deadlocks

If session A locks row 1 then wants row 2, while session B locks row 2 then wants row 1, both wait forever. Postgres detects this after a second and aborts one of them with deadlock detected. Prevent it by always locking rows in the same order (for example, by id), and keep transactions short.

Rules for healthy transactions

  • Keep them short. Never wait for user input or call a slow external API inside a transaction.
  • Don't leave sessions "idle in transaction": they hold locks and block VACUUM.
  • Let the database check rules atomically (UPDATE … WHERE stock >= 1, constraints, ON CONFLICT).
  • Be ready to retry on serialization failures and deadlocks.

Practice

  1. In one transaction, move 50 from Rahul to Asha, but ROLLBACK instead of committing. Confirm nothing changed.
  2. Write a transfer that should fail (move 10,000) and confirm both balances are unchanged afterwards.
  3. Use a savepoint to insert two accounts, where the second one fails, and keep the first.
PostgreSQL · editable
✎ Check your understanding

1.A statement inside BEGIN … COMMIT fails. What happens at COMMIT?

2.In PostgreSQL's MVCC, do readers block writers?

3.What's the safest way to decrement stock without overselling?

← Indexes and EXPLAIN