DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

๐Ÿ’ณ Transactions Explained Like You're 5

A bank transfer that can't be half-done

Day 48 of 149

๐Ÿ‘‰ Full deep-dive with code examples


The Bank Transfer

You transfer some money from savings to checking.

What if it crashed halfway?

  • Savings: -$100 โœ…
  • Checking: +$0 โŒ
  • The transfer is now inconsistent ๐Ÿ˜ฑ

Transactions prevent this!


All or Nothing

A transaction groups operations:

START TRANSACTION
  1. Take money from savings
  2. Add money to checking
COMMIT (make permanent)
Enter fullscreen mode Exit fullscreen mode

If anything fails โ†’ ROLLBACK (undo everything!)

Either BOTH happen or NEITHER happens.


The ACID Rules

Letter Meaning Example
A Atomic All or nothing
C Consistent Constraints/invariants stay true
I Isolated Others don't see half-done state
D Durable Once committed, it survives crashes

Real Example

BEGIN TRANSACTION;

UPDATE savings SET balance = balance - 100;
UPDATE checking SET balance = balance + 100;

COMMIT;  -- Make it permanent
-- or ROLLBACK; if something went wrong
Enter fullscreen mode Exit fullscreen mode

In One Sentence

Transactions ensure multiple database operations either all succeed together or all fail together, avoiding partially-applied state.


๐Ÿ”— Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)