DEV Community

Cover image for ๐Ÿ”ฅACID Properties with SQL Transactions
PRIAN S S 24CB042
PRIAN S S 24CB042

Posted on

๐Ÿ”ฅACID Properties with SQL Transactions

When working with databases, ACID properties are the foundation that ensures data reliability and consistency.
In this blog, weโ€™ll explore each property with SQL examples using a simple Accounts table.

๐Ÿฆ Step 1: Create Table and Insert Sample Data

CREATE TABLE Accounts (
acc_no INT PRIMARY KEY,
name VARCHAR(50),
balance INT
);

INSERT INTO Accounts VALUES (101, 'Alice', 5000);
INSERT INTO Accounts VALUES (102, 'Bob', 3000);
INSERT INTO Accounts VALUES (103, 'Charlie', 7000);

SELECT * FROM Accounts;

๐Ÿ…ฐ Atomicity

Definition: Atomicity ensures a transaction is all or nothing. If one part fails, the whole transaction is rolled back.
Example: Transfer money from Alice โ†’ Bob, but rollback before completion.
BEGIN TRANSACTION;

UPDATE Accounts SET balance = balance - 1000 WHERE acc_no = 101;

ROLLBACK;

SELECT * FROM Accounts;

๐Ÿ…ฒ Consistency

Definition: Consistency ensures that data follows defined rules and constraints.
Example: Prevent negative balance using a CHECK constraint.

ALTER TABLE Accounts
ADD CONSTRAINT chk_balance CHECK (balance >= 0);
INSERT INTO Accounts VALUES (104, 'David', -500);

๐Ÿ…ธ Isolation

Definition: Isolation ensures that concurrent transactions do not interfere with each other.

Example: Run two sessions at once.

SESSION 1 :
BEGIN TRANSACTION;
UPDATE Accounts SET balance = balance - 2000 WHERE acc_no = 103;

SESSION 2:
SELECT * FROM Accounts WHERE acc_no = 103;

๐Ÿ…ณ Durability

Definition: Durability ensures once a transaction is committed, it remains even after a system crash.

BEGIN TRANSACTION;
UPDATE Accounts SET balance = balance + 500 WHERE acc_no = 102;
COMMIT;

๐Ÿš€ Conclusion

*Through this demo, we saw how ACID properties guarantee:
*Atomicity โ†’ no partial updates.
*Consistency โ†’ rules are enforced.
*Isolation โ†’ transactions donโ€™t clash.
*Durability โ†’ committed changes survive crashes.

Thanks for @santhoshnc sir guiding me !!!

Top comments (0)