Careeroza
ACID Properties
ACID
Relational databases guarantee four properties for every transaction:
| Property | Meaning | Bank transfer example |
|---|---|---|
| Atomicity | all or nothing | debit and credit both happen, or neither |
| Consistency | moves the database from one valid state to another; constraints always hold | balance never goes below 0 if a CHECK forbids it |
| Isolation | concurrent transactions do not see each other's unfinished work | a report never sees money "in flight" |
| Durability | once committed, changes survive crashes | the transfer is still there after a power cut |
How Databases Provide ACID
- Write-ahead log (WAL / redo log): changes are written to a log before the data files, giving atomicity and durability.
- Undo / MVCC: old row versions let a transaction be rolled back and let readers see a consistent snapshot.
- Locks: prevent two transactions from changing the same row at once.
Atomicity in Action
Example
Asha tries to send 800 but only has 500. The debit changes 0 rows, so the application rolls back and the credit to Vikram is undone too:
CREATE TABLE Accounts (ID INT PRIMARY KEY, Owner TEXT, Balance DECIMAL(10,2) CHECK (Balance >= 0));
INSERT INTO Accounts VALUES (1, 'Asha', 500), (2, 'Vikram', 100);
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance + 800 WHERE ID = 2;
UPDATE Accounts SET Balance = Balance - 800 WHERE ID = 1 AND Balance >= 800; -- 0 rows changed
ROLLBACK; -- the application saw 0 rows changed, so it cancels the whole transfer
SELECT * FROM Accounts;Result: 2 rows
| ID | Owner | Balance |
|---|---|---|
| 1 | Asha | 500 |
| 2 | Vikram | 100 |