Lesson 5: SQL Transactions and Concurrency Control

Executive Summary:

Today we’re going to discuss SQL Transactions & Concurrency Control. As data integrity is rather important for databases, understanding how transactions function is critical. We’ll review what transactions are, how they should be used, and how they relate to concurrency control, which is critical in multi-user database environments. As usual, we’ll illustrate these concepts with examples.

Introduction to Transactions:

A transaction is a logical unit of work containing one or more SQL statements. A transaction is an atomic unit, which means it’s a single, indivisible unit. This means either all the changes made are saved to the database, or in the case of a transaction failure, none of the changes are saved. See the below example.

BEGIN TRANSACTION;
UPDATE Accounts SET balance = balance - 100 WHERE account_id = 1;
UPDATE Accounts SET balance = balance + 100 WHERE account_id = 2;
COMMIT;

Concurrency Control:

  • Locking:
    • SQL Server places locks automatically to prevent multiple users from updating the same data at the same time. When a transaction is updating a row, a lock prevents other transactions from modifying the same row at the same time.
  • Row Versioning:
    • Row Versioning allows multiple transactions access to the same row without waiting for other transactions to complete.

Handling Errors in Transactions:

Errors should be handled in all transactions; The rollback statement can be used to undo the changes attempted in the current statement.

BEGIN TRANSACTION;
BEGIN TRY
    -- Generate a divide-by-zero error.
    SELECT 1/0;
    COMMIT;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_MESSAGE() AS ErrorMessage;
    ROLLBACK;
END CATCH

Conclusion:

Understanding SQL transactions and error handling is crucial to maintain data integrity in SQL Server. Knowing this, you’ll be able to write more robust code and prevent issues caused by incorrect updates.

Leave a Reply

Your email address will not be published. Required fields are marked *