T-SQL Tutorial

SQL Server Consistency


Consistency is another one of the key properties of the ACID (Atomicity, Consistency, Isolation, Durability) database management system model. In SQL Server, consistency refers to the ability to ensure that the database remains in a valid state after a transaction is executed.

A database is considered consistent if it satisfies a set of predefined integrity constraints, such as unique keys, primary keys, and foreign keys. These constraints are used to define the relationships between tables and to ensure that the data is valid and accurate.


Example

Here's an example of how to enforce consistency in SQL Server using a transaction:

Suppose we have two tables, Customers and Orders, and we want to ensure that every order in the Orders table has a corresponding customer in the Customers table. We can use a transaction to ensure that no orders are inserted without a corresponding customer:

BEGIN TRANSACTION

DECLARE @CustomerId INT
SELECT @CustomerId = CustomerId FROM Customers WHERE CustomerName = 'John'

IF @CustomerId IS NULL
BEGIN
-- Customer does not exist, rollback the transaction
ROLLBACK TRANSACTION
PRINT 'Customer does not exist'
END
ELSE
BEGIN
-- Customer exists, insert the order
INSERT INTO Orders (CustomerId, OrderDate, TotalAmount)
VALUES (@CustomerId, GETDATE(), 100.00)

-- Commit the transaction
COMMIT TRANSACTION
PRINT 'Order added successfully'
END

In this example, we start a transaction and query the Customers table to find a customer with the name 'John'. If no customer is found, we rollback the transaction and print an error message. If a customer is found, we insert a new order into the Orders table using the customer's ID, and commit the transaction. By using a transaction, we ensure that the database is in a consistent state at all times, and that no orders are added without a corresponding customer.