π Introduction
Have you ever wondered what happens when two people try to withdraw money from the same bank account at the same time?
Databases handle such cases using transactions, locks, and recovery logs
to make sure data always stays consistent.
In this blog, weβll explore:
- How transactions maintain atomicity
- What a deadlock is and how itβs detected
- How log-based recovery ensures data safety after a crash
CREATE TABLE Accounts (
acc_no INT PRIMARY KEY,
name VARCHAR(50),
balance INT
);
INSERT INTO Accounts VALUES
(1, 'Alice', 1000),
(2, 'Bob', 1500),
(3, 'Charlie', 2000);
βοΈ 2οΈβ£ Transaction β Atomicity & Rollback
π§ Concept:
A transaction ensures that all steps succeed or none at all.
If any step fails, the database will rollback to the previous stable state.
START TRANSACTION;
UPDATE Accounts
SET balance = balance - 500
WHERE name = 'Alice';
UPDATE Accounts
SET balance = balance + 500
WHERE name = 'Bob';
SELECT * FROM Accounts;
ROLLBACK;
SELECT * FROM Accounts;
β
Result:
All updates are undone after rollback β no partial transaction is saved.
This proves Atomicity β either all or none of the operations take effect.
π 3οΈβ£ Deadlock Simulation
π§ Concept:
A deadlock happens when two transactions wait forever because each holds a lock the other needs.
Letβs simulate it using two SQL sessions.
πͺ Session 1:
START TRANSACTION;
UPDATE Accounts SET balance = balance - 100 WHERE name = 'Alice';
UPDATE Accounts SET balance = balance + 100 WHERE name = 'Bob';
πͺ Session 2:
START TRANSACTION;
UPDATE Accounts SET balance = balance - 50 WHERE name = 'Bob';
UPDATE Accounts SET balance = balance + 50 WHERE name = 'Alice';
π 4οΈβ£ Log-Based Recovery
π§ Concept:
Every database maintains logs (like MySQL Binary Logs or PostgreSQL WAL) that record each change.
If a crash happens, the DB can redo committed and undo uncommitted transactions.
SHOW VARIABLES LIKE 'log_bin';
START TRANSACTION;
UPDATE Accounts SET balance = 900 WHERE name = 'Alice';
ROLLBACK;
Then check the logs:
SHOW BINLOG EVENTS LIMIT 10;
Youβll see records for the update and rollback.
β
Result:
The undo operation is recorded, ensuring the database can recover correctly after any failure.
π§ Conclusion
Through this activity, we learned:
- Transactions ensure data integrity (Atomicity, Consistency)
- Deadlocks are automatically detected and handled by DBMS
- Logs help recover data during failures
π‘ Key takeaway: Databases are smart enough to protect your data even when things go wrong!





Top comments (0)