Keeping It Solid: ACID Principles in SQL Server Transactions

Mohamed Hendawy
2 min readDec 24, 2023

Introduction: In the database world, ACID (Atomicity, Consistency, Isolation, Durability) is like a superhero team ensuring that database transactions are reliable and solid. Let’s break down these principles and see how they work in SQL Server with easy-to-understand examples.

Section 1: Atomicity

Atomicity Defined

  • Think of atomicity as an all-or-nothing rule for transactions.
  • It’s like putting all your eggs in one basket: either you carry them all safely or drop the entire basket.

Query Example: Atomic Transaction

-- Example: Atomic Transaction
BEGIN TRANSACTION;

UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 123;

INSERT INTO TransactionLog (AccountID, Amount)
VALUES (123, -100);

COMMIT TRANSACTION;

If something goes wrong, we don’t partially update; we either do it all or none.

Section 2: Consistency

Consistency Defined

  • Consistency ensures that your database stays in a sensible state before and after a transaction.
  • It’s like making sure you have the right amount of cookies before and after sharing them.

Query Example: Consistent Transaction

-- Example: Consistent Transaction
BEGIN TRANSACTION;

UPDATE Products
SET StockQuantity = StockQuantity - 5
WHERE ProductID = 789;

-- Check for consistency
IF (SELECT StockQuantity FROM Products WHERE ProductID = 789) >= 0
BEGIN
COMMIT TRANSACTION;
END
ELSE
BEGIN
ROLLBACK TRANSACTION;
END;

We double-check that our action makes sense and only proceed if things stay sensible.

Section 3: Isolation

Isolation Defined

  • Isolation keeps one transaction from messing with another.

Query Example: Serializable Isolation

-- Example: Serializable Isolation
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;

-- Your transaction queries go here

COMMIT TRANSACTION;

We make sure nobody interrupts our work until we’re ready to share.

Section 4: Durability

Durability Defined

  • Durability ensures that once something is written in the database, it stays there — even if the power goes out.
  • It’s like writing your diary in pen; it’s there to stay.

Query Example: Durable Transaction

-- Example: Durable Transaction
BEGIN TRANSACTION;

UPDATE CustomerInfo
SET Email = 'newemail@example.com'
WHERE CustomerID = 456;

-- Ensure the transaction is durable
CHECKPOINT;

We save our changes so that they survive even if something unexpected happens.

Conclusion: ACID principles are like the superheroes of database transactions, ensuring things stay reliable and consistent. In simple terms, we either do everything or nothing (atomicity), keep things sensible (consistency), work in our own space (isolation), and make sure changes stick around (durability). The SQL examples show how these principles are superheroes, ensuring our database world stays solid and dependable.

--

--