# Transactions & ACID

> Group several statements into one all-or-nothing step with BEGIN and COMMIT, and learn what ACID promises and what a failed transaction does.

Subject: SQL | Lesson 32 of 44 | 7 min read
Interactive lesson: https://codewithanimation.in/sql/transactions-and-acid
Previous: [RETURNING & Upsert](https://codewithanimation.in/sql/returning-and-upsert.md) | Next: [Isolation Levels](https://codewithanimation.in/sql/isolation-levels.md)

## All or nothing

A **transaction** bundles several statements into one all-or-nothing step. You open it with `BEGIN`, run your statements, then end it with `COMMIT` to keep every change, or `ROLLBACK` to throw them all away.

Even without `BEGIN`, every single statement is its own tiny transaction: it is committed on its own as soon as it succeeds. Only a block between `BEGIN` and `COMMIT` groups several statements together.

## Money must not appear or vanish

Moving 100 from Alice to Bob takes two updates: take 100 from Alice, add 100 to Bob. If the program crashes between them, one account is changed and the other is not. A transaction makes the two updates succeed together or fail together.

## A transfer in a transaction

```sql
BEGIN;
UPDATE accounts SET balance = balance + 40 WHERE name = 'Bob';
UPDATE accounts SET balance = balance - 40 WHERE name = 'Alice';
COMMIT;
```

After the first update, this session sees Bob with 90, but every other session still sees 50. After `COMMIT`, everyone sees both changes at the same moment.

ACID is the short name for four promises. **Atomic**: all or nothing. **Consistent**: the rules (constraints) hold before and after. **Isolated**: other sessions do not see half-finished work. **Durable**: once COMMIT is reported, the change is saved to disk and survives a crash.

## Common mistake: Failure, aborted state and savepoints

Suppose the table has `CHECK (balance >= 0)` and you move 150 from Alice, who has only 100. The credit to Bob works, then the debit from Alice fails. Inside a transaction, PostgreSQL marks it aborted and ignores everything until you end it. Even `COMMIT` then just rolls back, and Bob's credit is undone.

Without `BEGIN`, the first update was already committed on its own. Bob keeps the 150 while Alice still has 100: money has appeared from nowhere. This is the bug transactions exist to prevent.

A **savepoint** lets you undo only part of a transaction: `SAVEPOINT s;` then `ROLLBACK TO s;` throws away the work since `s` and keeps the rest. It is also the only way to carry on in a transaction block after an error.

Keep transactions short. An open transaction can hold locks, and the next lessons show why that matters.

## Tip: One business action, one transaction

Wrap statements that must succeed together, such as a transfer, an order with its order lines, or an insert with its audit record, in one `BEGIN ... COMMIT`. If your code catches an error, make sure it issues `ROLLBACK`.

## Try it: Move money, with and without BEGIN

Step through a transfer of 40, then a transfer of 150. Switch off the transaction and watch what the other sessions see after the failure.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/transactions-and-acid

## Check yourself

### Question 1

Inside a transaction, a session has updated Bob's balance but has not committed. What do other sessions see?

- A. The old balance, until COMMIT
- B. The new balance at once
- C. An error, because the row is busy

Correct answer: A

This is the isolation promise: other sessions see the changes only after COMMIT, all at once.

- Why not B: Updates by an open transaction are invisible to other transactions until it completes.
- Why not C: Reading never fails or waits because of someone else's uncommitted change.

### Question 2

No BEGIN was issued. The first UPDATE of a two-step transfer works and the second fails. What is the state of the first UPDATE?

- A. Committed, because each statement is its own transaction
- B. Rolled back automatically
- C. Waiting for the second UPDATE

Correct answer: A

Without BEGIN, each statement commits by itself. Group statements with BEGIN so they stand or fall together.

- Why not B: Only a transaction block rolls back together. A lone statement is committed as soon as it succeeds.
- Why not C: Nothing waits. The database does not know the two updates belong together.

### Question 3

A statement inside a transaction fails with an error. What does PostgreSQL do with the next commands?

- A. Ignores them until you end the transaction (ROLLBACK, or ROLLBACK TO a savepoint)
- B. Runs them as normal
- C. Rolls back only the failed statement and carries on

Correct answer: A

After an error the transaction is aborted. Only ROLLBACK (or ROLLBACK TO a savepoint) gets you out.

- Why not B: The transaction is aborted. It refuses further commands: current transaction is aborted, commands ignored until end of transaction block.
- Why not C: That would need a savepoint. By default the whole transaction is aborted.

## Remember this

- BEGIN ... COMMIT makes several statements one all-or-nothing step. ROLLBACK cancels them all.
- ACID: atomic (all or nothing), consistent (rules hold), isolated (half-finished work is invisible), durable (committed means saved).
- Without BEGIN, every statement is committed on its own.
- After an error a transaction is aborted. Use ROLLBACK, or SAVEPOINT and ROLLBACK TO to undo just part of it.
