DEV Community

BHARANIKA D 24CB005
BHARANIKA D 24CB005

Posted on

๐Ÿ’พ ACID Properties

๐Ÿ’พ 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)