Transactions

A transaction groups several database changes so they happen all together or not at all — even if the server crashes halfway.

Transfer ₹500: Asha → Ravi

asha₹1000
ravi₹1000

Total on disk: ₹2000

Statements (each saved on its own)

  1. nothing yet

Two updates must happen together: take ₹500 from Asha, give ₹500 to Ravi. The bank's total must stay ₹2,000.

Step 1 / 4
Bank total (on disk)
₹2000

What's happening?

  1. A transfer needs two updates: take money from one account and add it to the other.
  2. Without a transaction, each update is saved on its own; a crash in between leaves the money half-moved.
  3. Inside a transaction, nothing is permanent until COMMIT. After a crash, the database rolls back anything not committed.

Where you'll meet it

Payments, bookings, stock levels, sign-ups that create several rows — anything where a half-done change would be wrong.

Common mistake

Calling external services (payment APIs, emails) inside a long transaction: locks are held while you wait, and a rollback cannot undo the email.

FAQ

What does ACID stand for?

Atomic (all or nothing), Consistent (rules still hold), Isolated (others don't see half-done work), Durable (committed means saved).

How does the database undo work after a crash?

It writes every change to a log before applying it. On restart it replays committed transactions and undoes the rest.

Do transactions prevent race conditions?

They help, but two transactions can still read the same old value. Locks (SELECT … FOR UPDATE) or constraints close the gap — see Race Condition.