Transfer $100 from A to B. Two writes: deduct from one, add to the other.
What happens if the database crashes between them?
WITHOUT A TRANSACTION
Write one succeeds. Write two fails. Account A is down $100, account B never
received it, and the money exists nowhere. Nothing is "broken" — every
individual statement did exactly what it was told. The data is just wrong.
That's a partial update, and it's the problem transactions exist to solve.
WITH A TRANSACTION
BEGIN
deduct $100 from A
add $100 to B
COMMIT
The two writes become one logical unit. Both land, or neither does.
If the second write fails, ROLLBACK undoes the first. Both balances return
to exactly where they started — as if the attempt never happened. No
half-finished state to clean up later.
THAT'S THE A IN ACID
• Atomicity — all or nothing
• Consistency — valid state to valid state
• Isolation — concurrent transactions don't tangle
• Durability — once committed, it survives a crash
THE PART WORTH KNOWING
A transaction protects *the database*. It does not protect everything else.
If your code sent a confirmation email, charged a card, or called an
external API before the rollback, none of that reverses. The database is
clean; the outside world isn't. That's why side effects belong outside the
transaction — or behind `after_commit`, so they only fire once the data is
genuinely saved.
Transactions give you a consistent database. They don't give you a
distributed undo button.
—
#Astmation — #software #systems, #automation, and #AI-powered #applications .
Smart Technology. Smarter Solutions.
https://astmation.com/
#Shorts #Database #SQL #ACID #Transactions #PostgreSQL #BackendDevelopment #DataIntegrity #SoftwareEngineering #LearnToCode
Watch on YouTube