Last modified: March 23, 2026

This article is written in: πŸ‡ΊπŸ‡Έ

Database Transactions

Database transactions are a cornerstone of reliable data management. They let an application bundle multiple low-level reads and writes into a single, all-or-nothing unit so the database moves cleanly from one consistent state to anotherβ€”even when dozens of users race to change the same rows or hardware glitches interrupt the process. Transactions offer the developer a simple success/ failure switch while the engine handles locking, logging, versioning, and recovery behind the scenes.

|            Application (Transaction Context)                |
|                                                             |
|   BEGIN TRANSACTION  ──►   Perform SQL/CRUD Operations      |
|                                                             |
|   COMMIT  ◄── Success? ────── Yes ───┐                      |
|                                      β”‚                      |
|   ROLLBACK ◄── On error or cancel β”€β”€β”€β”˜                      |
+-------------------------------------------------------------+

A typical flow starts with BEGIN (or an implicit start), runs several statements that may touch many tables, then finishes with COMMIT to make every change permanentβ€”or ROLLBACK to annul them if any step fails.

Practical SQL Examples

-- Basic transaction: transfer $200 between accounts (PostgreSQL)
BEGIN;
  UPDATE accounts SET balance = balance - 200 WHERE id = 1;
  UPDATE accounts SET balance = balance + 200 WHERE id = 2;
COMMIT;

-- Explicit error handling with savepoints
BEGIN;
  INSERT INTO orders (customer_id, total) VALUES (42, 99.95);

  SAVEPOINT before_inventory;
  UPDATE inventory SET qty = qty - 1 WHERE product_id = 7;
  -- If the update fails (e.g., CHECK constraint: qty >= 0):
  ROLLBACK TO before_inventory;

  -- Retry with a different fulfilment path
  INSERT INTO backorders (product_id, customer_id) VALUES (7, 42);
COMMIT;

-- Setting an isolation level for a critical read
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN;
  SELECT balance FROM accounts WHERE id = 1;
  UPDATE accounts SET balance = balance - 50 WHERE id = 1;
COMMIT;

ACID: The Core Properties

Isolation Levels

Isolation levels control how much of one transaction's uncommitted work is visible to others. Moving from the weakest to the strongest level trades concurrency for correctness.

Isolation Level Anomaly Spectrum

  READ            READ            REPEATABLE        SERIALIZABLE
  UNCOMMITTED     COMMITTED       READ
  ─────────────►──────────────►──────────────────►──────────────────►
  β”‚               β”‚               β”‚                  β”‚
  β”‚ Dirty Reads   β”‚               β”‚                  β”‚
  β”‚ Non-Repeat.   β”‚ Non-Repeat.   β”‚                  β”‚
  β”‚ Phantoms      β”‚ Phantoms      β”‚ Phantoms         β”‚ (no anomalies)
  β”‚               β”‚               β”‚                  β”‚
  ◄── Fastest ────────────────────────────── Slowest / Safest ──►

READ UNCOMMITTED

READ COMMITTED

REPEATABLE READ

SERIALIZABLE

Isolation Levels Comparison

Level Dirty Read Non-Repeatable Read Phantom Read Typical Default In
READ UNCOMMITTED Possible Possible Possible β€”
READ COMMITTED βœ— Possible Possible PostgreSQL, Oracle, SQL Server
REPEATABLE READ βœ— βœ— Possible MySQL / InnoDB
SERIALIZABLE βœ— βœ— βœ— Selected explicitly

Dealing with Single-Object Writes

Single-Object Write Flow
+-------------------------+
|        BEGIN            |
+-------------+-----------+
              |
              v
+-------------------------+
|  Lock / Version Check   |
+-------------+-----------+
              |
              v
+-------------------------+
|     Apply the Write     |
+-------------+-----------+
              |
              v
+-------------------------+
|   COMMIT or ROLLBACK    |
+-------------------------+
Write-Ahead Logging (WAL) Flow

  Client                      WAL (on disk)              Data Pages (on disk)
    β”‚                              β”‚                              β”‚
    β”‚  1. BEGIN + UPDATE row 42    β”‚                              β”‚
    │─────────────────────────►    β”‚                              β”‚
    β”‚                              β”‚                              β”‚
    β”‚                     2. Append redo                          β”‚
    β”‚                        log entry ──►  [LSN 101: row 42     β”‚
    β”‚                                        old=A, new=B]       β”‚
    β”‚                              β”‚                              β”‚
    β”‚  3. COMMIT                   β”‚                              β”‚
    │─────────────────────────►    β”‚                              β”‚
    β”‚                     4. fsync commit                         β”‚
    β”‚                        record to disk                      β”‚
    β”‚  ◄── 5. ACK ────────────    β”‚                              β”‚
    β”‚                              β”‚                              β”‚
    β”‚                              β”‚    6. Checkpoint             β”‚
    β”‚                              β”‚    (lazy background write)   β”‚
    β”‚                              │──────────────────────►       β”‚
    β”‚                              β”‚    Data page updated         β”‚

Advanced Transaction Management

Complex workloads touch many independent resourcesβ€”multiple tables, shards, or even distinct databasesβ€”so additional coordination layers are required.

Two-Phase Commit (2PC)

Coordinator                                   Participant(s)
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ 1. PREPARE                    β”‚        β”‚ Receive PREPARE                β”‚
β”‚    (Ask participants to vote) β”‚ ────►  β”‚ Validate / Pre-commit          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜        β”‚                                β”‚
            β–²                            β”‚ Send VOTE (YES / NO)           β”‚
            β”‚                            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
            β”‚                                            β”‚
            └─────────────── 2. VOTES β—„β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

                       Decision Phase
                           β”‚
                           β–Ό

               β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
               β”‚ 3. DECISION             β”‚
               β”‚                         β”‚
               β”‚ All YES  β†’ COMMIT       β”‚
               β”‚ Any NO   β†’ ROLLBACK     β”‚
               β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Deadlock Detection and Prevention

Deadlock Example
   Transaction A          Transaction B
      |                        |
   lock X                  lock Y
      |                        |
   wait Y  ◄────────────── wait X
      |                        |
   (circular wait β†’ deadlock)

Savepoints

Savepoints let you mark intermediate positions inside a running transaction so you can roll back to that point without aborting the entire transaction.

Savepoints within a Transaction

  BEGIN
    β”‚
    β”œβ”€β”€ INSERT INTO orders ...
    β”‚
    β”œβ”€β”€ SAVEPOINT sp1 ◄──────────────── mark
    β”‚     β”‚
    β”‚     β”œβ”€β”€ UPDATE inventory ...
    β”‚     β”‚
    β”‚     └── (error) β†’ ROLLBACK TO sp1   ◄── partial undo
    β”‚
    β”œβ”€β”€ INSERT INTO backorders ...         ◄── continue normally
    β”‚
    └── COMMIT                             ◄── everything except
                                                the rolled-back part

Concurrency Control Methods Comparison

Method Underlying Mechanism Pros Cons Typical Scenarios
Locks Pessimistic read/write locks Strong consistency; simple mental model Blocking, deadlocks, lock-escalation overhead OLTP systems where conflicts are frequent
MVCC Append row versions + snapshot reads Readers never block writers; high read scalability Vacuuming/garbage collection; more I/O for version churn Mixed read-heavy workloads (PostgreSQL, InnoDB)
Timestamps Assign global time/order to Txns Easy to serialize logically; no blocking High abort rate if contention; clock or logical-counter drift In-memory or distributed DBs (Spanner, FoundationDB)
Optimistic Validate at commit (compare‐and‐swap) Near-zero overhead during read phase; suits low contention Late failures waste work; write-write conflicts cause retries Microservices or mobile apps with rare collisions