DEV Community

Cover image for SQL Transactions — The Complete Guide (Internals, ACID, Isolation, Locks, Logs, and Real-World Code)
Farhad Rahimi Klie
Farhad Rahimi Klie

Posted on • Edited on

SQL Transactions — The Complete Guide (Internals, ACID, Isolation, Locks, Logs, and Real-World Code)

Transactions are the foundation of data integrity in SQL databases.
If you work with banking systems, payments, e-commerce, social networks, or any serious backend, you are already relying on transactions—even if you don’t fully understand them yet.

This article explains everything about SQL transactions, from high-level concepts to internal database mechanisms, with clear SQL code examples.


1. What Is a Transaction?

A transaction is a logical unit of work that groups one or more SQL statements into a single, atomic operation.

Simple definition:

A transaction ensures that either all operations succeed or none of them do.

Example:

BEGIN;

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

COMMIT;
Enter fullscreen mode Exit fullscreen mode

If any statement fails → nothing is applied.


2. Why Transactions Exist

Without transactions, databases would suffer from:

  • Partial updates
  • Corrupted data
  • Inconsistent state
  • Lost money
  • Race conditions

Example without transaction (dangerous):

UPDATE accounts SET balance = balance - 100 WHERE id = 1;
-- crash happens here
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
Enter fullscreen mode Exit fullscreen mode

Money disappears.


3. ACID Properties (Core Theory)

Every SQL transaction follows ACID.


3.1 Atomicity

All or nothing.

Either:

  • All statements execute successfully or
  • Database rolls back everything

Example:

BEGIN;
INSERT INTO orders VALUES (1, 'phone');
INSERT INTO payments VALUES (1, 500);
ROLLBACK;
Enter fullscreen mode Exit fullscreen mode

Nothing is stored.


3.2 Consistency

The database always moves from one valid state to another valid state.

Rules include:

  • Constraints
  • Foreign keys
  • Triggers
  • Data types

Example:

INSERT INTO users (id, email) VALUES (1, NULL);
-- fails if email is NOT NULL
Enter fullscreen mode Exit fullscreen mode

Transaction is rejected.


3.3 Isolation

Transactions do not see each other’s intermediate states.

Multiple users can work concurrently without corrupting data.

Isolation is controlled by isolation levels (explained later).


3.4 Durability

Once committed, data survives crashes, power failures, and restarts.

Achieved via:

  • Write-Ahead Logging (WAL)
  • Redo logs
  • Disk flush guarantees

4. Transaction Lifecycle (Internals)

Internally, a transaction goes through these phases:

  1. BEGIN
  2. Execution
  3. Validation
  4. Commit or Rollback
  5. Cleanup

Internal flow:

Client → SQL Engine → Transaction Manager
        ↓
      Lock Manager
        ↓
      Buffer Pool
        ↓
      WAL / Redo Log
Enter fullscreen mode Exit fullscreen mode

5. Transaction Commands in SQL

5.1 BEGIN / START TRANSACTION

BEGIN;
-- or
START TRANSACTION;
Enter fullscreen mode Exit fullscreen mode

Starts a new transaction.


5.2 COMMIT

COMMIT;
Enter fullscreen mode Exit fullscreen mode
  • Writes changes permanently
  • Flushes logs to disk

5.3 ROLLBACK

ROLLBACK;
Enter fullscreen mode Exit fullscreen mode
  • Undoes all changes
  • Releases locks

5.4 SAVEPOINT (Partial Rollback)

BEGIN;

INSERT INTO users VALUES (1, 'Ali');
SAVEPOINT s1;

INSERT INTO users VALUES (2, NULL); -- error

ROLLBACK TO s1;
COMMIT;
Enter fullscreen mode Exit fullscreen mode

User 1 is saved; user 2 is not.


6. Auto-Commit Mode

Most SQL databases use auto-commit by default.

INSERT INTO users VALUES (1, 'Sara');
Enter fullscreen mode Exit fullscreen mode

Each statement = one transaction.

Disable auto-commit:

SET autocommit = 0;
Enter fullscreen mode Exit fullscreen mode

7. Isolation Levels (Very Important)

SQL defines four isolation levels.


7.1 READ UNCOMMITTED

  • Can see dirty data
  • Rarely used

Problem: Dirty Read

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
Enter fullscreen mode Exit fullscreen mode

7.2 READ COMMITTED (Default in many DBs)

  • Sees only committed data
  • Prevents dirty reads

Problem: Non-Repeatable Read


7.3 REPEATABLE READ

  • Same query always returns same result
  • Prevents non-repeatable reads

Problem: Phantom Reads

(MySQL InnoDB solves this with MVCC)


7.4 SERIALIZABLE (Strongest)

  • Transactions behave as if executed one by one
  • Slowest but safest
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
Enter fullscreen mode Exit fullscreen mode

8. Concurrency Problems (With Examples)

Dirty Read

Reading uncommitted data.

Non-Repeatable Read

SELECT balance FROM accounts WHERE id = 1;
-- another transaction updates it
SELECT balance FROM accounts WHERE id = 1;
Enter fullscreen mode Exit fullscreen mode

Different results.

Phantom Read

SELECT * FROM orders WHERE amount > 100;
-- another transaction inserts a new row
SELECT * FROM orders WHERE amount > 100;
Enter fullscreen mode Exit fullscreen mode

9. Locks (Internal Mechanism)

Transactions use locks to protect data.

9.1 Types of Locks

  • Shared (S) – Read
  • Exclusive (X) – Write
  • Intent Locks
  • Row-level locks
  • Table-level locks

Example:

SELECT * FROM users WHERE id = 1 FOR UPDATE;
Enter fullscreen mode Exit fullscreen mode

Locks the row.


10. MVCC (Multi-Version Concurrency Control)

Modern databases (PostgreSQL, MySQL InnoDB) use MVCC.

How MVCC works:

  • Each row has versions
  • Transactions see a snapshot
  • Readers don’t block writers

Internal fields:

  • xmin (created by)
  • xmax (deleted by)

11. Write-Ahead Logging (WAL)

Transactions do not write directly to disk.

Rule:

Log first, data later

Steps:

  1. Write changes to WAL
  2. Commit log to disk
  3. Apply data pages asynchronously

This ensures durability.


12. Rollback Internals

Rollback uses:

  • Undo logs
  • Before-images of rows

Rollback is logical, not physical.


13. Deadlocks

A deadlock occurs when two transactions wait on each other.

Example:

T1 locks A → waits for B
T2 locks B → waits for A
Enter fullscreen mode Exit fullscreen mode

Database:

  • Detects deadlock
  • Kills one transaction

14. Nested Transactions (Truth)

SQL does not truly support nested transactions.

What exists:

  • Savepoints (pseudo-nested)
SAVEPOINT s1;
ROLLBACK TO s1;
Enter fullscreen mode Exit fullscreen mode

15. Distributed Transactions (Brief)

Used across multiple databases.

Techniques:

  • Two-Phase Commit (2PC)
  • XA Transactions

Very expensive and complex.


16. Transactions in Real Applications

Banking

  • Transfers
  • Payments
  • Ledgers

E-commerce

  • Orders
  • Inventory updates
  • Payments

Social Media

  • Likes
  • Follows
  • Counters

17. Best Practices

  • Keep transactions short
  • Avoid user input inside transactions
  • Always handle rollback
  • Choose correct isolation level
  • Never assume auto-commit behavior

18. Full Real-World Example

BEGIN;

INSERT INTO orders (id, user_id, total) VALUES (1, 10, 500);
INSERT INTO order_items VALUES (1, 'Laptop', 500);
UPDATE inventory SET stock = stock - 1 WHERE product = 'Laptop';

COMMIT;
Enter fullscreen mode Exit fullscreen mode

If any step fails → ROLLBACK.


19. Summary

Transactions are not optional.
They are the core guarantee behind reliable databases.

You now understand:

  • ACID
  • Internals
  • Isolation levels
  • Locks
  • MVCC
  • WAL
  • Deadlocks
  • Real-world usage

Mastering transactions means you think like a database engineer, not just a SQL user.

Top comments (0)