BEGIN TRANSACTION
UPDATE accounts SET balance = balance - 1000 WHERE account_id = 'user1';
-- System crash occurs! ๐ฅ
UPDATE accounts SET balance = balance + 1000 WHERE account_id = 'user2';
COMMIT;
-- System lost money ๐ฑ
BEGIN TRANSACTION
UPDATE accounts SET balance = balance - 1000 WHERE account_id = 'user1';
-- System detects failure
ROLLBACK; -- Revert all changes
-- Either full success or full failure
Click to see atomicity violation...
-- Rule: Account balance cannot be below $500
UPDATE accounts SET balance = 200 WHERE account_id = 'user1';
-- Business rule violated! Balance < $500
UPDATE accounts SET balance = balance - 1000 WHERE account_id = 'user1';
-- No corresponding addition! Money lost!
BEGIN TRANSACTION
-- Check constraints before update
IF (balance - 1000) >= 500 THEN
UPDATE accounts SET balance = balance - 1000 WHERE account_id = 'user1';
UPDATE accounts SET balance = balance + 1000 WHERE account_id = 'user2';
COMMIT;
ELSE
ROLLBACK; -- Maintain consistency
END IF;
Click to see consistency violation...
-- Transaction 1 (User1)
BEGIN TRANSACTION
UPDATE accounts SET balance = 15000 WHERE account_id = 'community';
-- User2 sees balance = 15000 (dirty read!)
ROLLBACK; -- Transaction 1 fails
-- Transaction 1 (User1)
BEGIN TRANSACTION
SELECT balance FROM accounts WHERE account_id = 'community' FOR UPDATE;
-- Row locked, User2 must wait
UPDATE accounts SET balance = 15000 WHERE account_id = 'community';
COMMIT; -- Lock released
Click to see isolation violation...
BEGIN TRANSACTION
UPDATE accounts SET balance = balance + 5000 WHERE account_id = 'community';
COMMIT; -- Transaction successfully committed
-- Power failure occurs! ๐กโก
-- Data was only in memory, not written to disk
-- After restart: Changes lost! ๐ฑ
BEGIN TRANSACTION
-- Write to log file first (WAL)
LOG: "UPDATE accounts SET balance = balance + 5000 WHERE account_id = 'community'"
-- Flush log to disk
UPDATE accounts SET balance = balance + 5000 WHERE account_id = 'community';
COMMIT; -- Guaranteed permanent
Click to see durability violation...