Video in progress

What is a transaction, and what do the letters in ACID stand for?

A transaction is a group of operations executed as one unit: either everything is saved or nothing is. ACID is Atomicity, Consistency, Isolation, Durability: all-or-nothing execution, rules never being violated, concurrent transactions not interfering with each other, and no data loss after a commit.

📖 Answer

The classic example is a money transfer:

BEGIN;
UPDATE accounts SET balance = balance - 100000 WHERE id = 1;
UPDATE accounts SET balance = balance + 100000 WHERE id = 2;
COMMIT;

If the server dies after the first UPDATE, the money must not vanish into thin air. A transaction guarantees that.

  • Atomicity: both UPDATEs happen together or not at all.
  • Consistency: if a constraint (CHECK (balance >= 0), an FK) would be violated, the transaction doesn't commit.
  • Isolation: another session doesn't see the half-finished state (how much it is hidden depends on the isolation level).
  • Durability: once COMMIT returns, the data has been written to disk through the WAL and survives a server restart.

In Java you usually don't write BEGIN yourself: in Spring, @Transactional opens a transaction at the start of the method, commits at the end, and rolls back if a RuntimeException is thrown.