The ACID properties in SQL Server are fundamental principles that ensure database transactions are processed reliably. Each property represents a key aspect of transaction management.
Atomicity ensures that a transaction is treated as a single, indivisible unit of work. Either all operations within the transaction succeed, or none of them are applied.
BEGIN TRANSACTION;
BEGIN TRY
INSERT INTO Accounts (AccountID, Balance) VALUES (1, 1000);
UPDATE Accounts SET Balance = Balance - 500 WHERE AccountID = 1;
INSERT INTO Accounts (AccountID, Balance) VALUES (2, 500);
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
PRINT ERROR_MESSAGE();
END CATCH;
If any operation (e.g., the update or second insert) fails, the entire transaction is rolled back.
Consistency ensures that the database transitions from one valid state to another. A transaction should always leave the database in a consistent state, adhering to all constraints, cascades, triggers, and rules.
-- Consider a `Bank` table with a constraint: Total balance must not exceed $10,000.
CREATE TABLE Bank (
AccountID INT PRIMARY KEY,
Balance INT CHECK (Balance <= 10000)
);
-- Invalid Transaction
BEGIN TRANSACTION;
UPDATE Bank SET Balance = Balance + 11000 WHERE AccountID = 1;
-- This violates the CHECK constraint and will fail.
COMMIT TRANSACTION;
The database ensures that constraints are enforced, maintaining consistency.
Isolation ensures that concurrent transactions do not interfere with each other. Depending on the isolation level, a transaction can see intermediate states of other transactions or only their final states.
-- Transaction 1
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
UPDATE Products SET Stock = Stock - 1 WHERE ProductID = 101;
-- Hold the transaction open without committing.
-- Transaction 2
BEGIN TRANSACTION;
SELECT Stock FROM Products WHERE ProductID = 101;
-- The stock shown depends on the isolation level.
COMMIT TRANSACTION;
The isolation level (e.g., READ UNCOMMITTED, SERIALIZABLE) determines how much a transaction is "isolated" from others.
Durability ensures that once a transaction is committed, its changes are permanent, even in the event of a system failure.
BEGIN TRANSACTION;
INSERT INTO Orders (OrderID, ProductID, Quantity) VALUES (1, 101, 5);
COMMIT TRANSACTION;
-- After committing, the data remains safe even if the server crashes.
SQL Server uses transaction logs to ensure changes are written to disk and can be recovered.
BEGIN TRANSACTION;
BEGIN TRY
UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 1; -- Debit
UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 2; -- Credit
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
PRINT ERROR_MESSAGE();
END CATCH;
These properties ensure data integrity, consistency, and reliability, making them vital for robust database systems.