DEV Community

Baviya Varshini V
Baviya Varshini V

Posted on

💾 Understanding ACID Properties in Databases with SQL Examples

In this post, I’ll demonstrate ACID properties — Atomicity, Consistency, Isolation, and Durability — using a simple Accounts table and a few SQL commands.

Let’s dive in 👇

🧾 1. Table Creation

CREATE TABLE Accounts (
  acc_no INT PRIMARY KEY,
  name VARCHAR(50),
  balance INT CHECK (balance >= 0)
);

Enter fullscreen mode Exit fullscreen mode

🧩 2. Insert Sample Data

INSERT INTO Accounts VALUES (101, 'Baviya', 3000);
INSERT INTO Accounts VALUES (102, 'Karthik', 4000);
INSERT INTO Accounts VALUES (103, 'Anu', 7000);

Enter fullscreen mode Exit fullscreen mode

⚙️ 3. Atomicity Test (All or Nothing)

Goal: Start a transaction to transfer ₹1000 from Baviya to Karthik but rollback midway — no changes should remain.

-- Start Transaction
START TRANSACTION;

-- Subtract 1000 from Baviya
UPDATE Accounts SET balance = balance - 1000 WHERE acc_no = 101;

-- Add 1000 to Karthik
UPDATE Accounts SET balance = balance + 1000 WHERE acc_no = 102;

-- Now ROLLBACK (cancel transaction)
ROLLBACK;

-- Check balances again
SELECT * FROM Accounts;

Enter fullscreen mode Exit fullscreen mode

🧱 4. Consistency Test (Valid State → Valid State)

Goal: Try inserting invalid (negative) balance.

INSERT INTO Accounts VALUES (104, 'InvalidUser', -500);

Enter fullscreen mode Exit fullscreen mode

🔒 5. Isolation Test (One transaction shouldn’t see another’s uncommitted changes)
Session 1:

START TRANSACTION;
UPDATE Accounts SET balance = balance - 500 WHERE acc_no = 101;
-- Don’t commit yet!

Enter fullscreen mode Exit fullscreen mode

Session 2:

SELECT * FROM Accounts WHERE acc_no = 101;
COMMIT;

Enter fullscreen mode Exit fullscreen mode

💾 6. Durability Test (Data survives restart)

START TRANSACTION;
UPDATE Accounts SET balance = balance + 200 WHERE acc_no = 103;
COMMIT;

Enter fullscreen mode Exit fullscreen mode
SELECT * FROM Accounts WHERE acc_no = 103;

Enter fullscreen mode Exit fullscreen mode

✅ Conclusion

We successfully verified all ACID properties:

Top comments (0)