Sikau

Databases and SQL · Day 15 · about 30 min

Transactions

All or nothing: BEGIN, COMMIT, ROLLBACK.

Half a payment is worse than none

Moving Rs 500 from one wallet to another is two updates. If the server crashes between them, money vanishes. A transaction groups statements so they all happen — or none do. That's the A in ACID: Atomicity.

BEGIN … COMMIT / ROLLBACK

CREATE TABLE wallets (owner text PRIMARY KEY, balance int NOT NULL CHECK (balance >= 0));
INSERT INTO wallets VALUES ('Asha', 1000), ('Bikash', 200);

BEGIN;
UPDATE wallets SET balance = balance - 500 WHERE owner = 'Asha';
UPDATE wallets SET balance = balance + 500 WHERE owner = 'Bikash';
COMMIT;

BEGIN;
UPDATE wallets SET balance = balance - 5000 WHERE owner = 'Bikash';
ROLLBACK;

SELECT * FROM wallets ORDER BY owner;
  • ACID: Atomic (all or nothing), Consistent (constraints hold), Isolated (concurrent transactions don't see half-done work), Durable (committed data survives crashes).
  • In apps, your driver or ORM wraps transactions: await prisma.$transaction([...]).
  • Keep transactions short — they can hold locks other requests wait for.

The rest of this lesson

  • Errors inside a transactionexplain
  • Concurrency and locksexplain
  • What's Asha's balance?predict
  • A safe transferorder
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 17 lessons of Databases and SQL