Types of Transactions in SQL Server

Types of Transactions in SQL Server

Transactions are like safety nets for databases in SQL Server. They help keep data safe and consistent by making sure that when we make changes, they all happen together or none at all. If something goes wrong, transactions allow us to undo everything, avoiding half-done updates. They're essential for reliable database operations and prevent strange data issues. Transactions also let many people work on the database at the same time without messing things up.


In this article, I aim to showcase the types of transactions in SQL Server and explain how to apply them in various scenarios.


There are three main types of transactions in sql server:

1- Auto Commit Transaction Mode in SQL Server

2- Implicit Transaction Mode in SQL Server

3- Explicit Transaction Mode in SQL Server


I will use the following table to explain the various types of transactions in SQL Server.

CREATE TABLE Person
(
    Id INT PRIMARY KEY,
    FirstName VARCHAR(50),
    LastName VARCHAR(50)
)        

1- Auto Commit Transaction Mode in SQL Server:

This is the default transaction mode in SQL Server. In this transaction mode, each SQL statement is treated as a separate transaction. In this Transaction Mode, as a developer, we are not responsible for either beginning the transaction (i.e. Begin Transaction) or ending a transaction (i.e. either Commit or Roll Back). Whenever we execute any DML statement, the SQL Server will automatically begin the transaction as well as end the transaction with a Commit or Rollback i.e. if the transaction is completed successfully, it is committed. If the transaction faces any error, it is rolled back. So the programmer does not have any control over them.

I'll provide an example for clarification:

INSERT INTO Person VALUES (1, ‘Nadim’, ‘Attar’)

INSERT INTO Person VALUES (1, ‘Belal’, ‘Attar’)

The first insert will execute successfully, but the second insert will throw the following exception: "Violation of Primary Key Constraint. Cannot insert duplicate key in object 'dbo.Person'"

2- Implicit Transaction Mode in SQL Server:

In the Implicit mode of transaction, the SQL Server is responsible for beginning the transaction implicitly before the execution of any DML statement and the developers are responsible to end the transaction with a commit or rollback. Once the transaction is ended ie. once the developer executes either the commit or rollback command, then automatically a new transaction will start by SQL Server. That means, in the case of implicit mode, a new transaction will start automatically by SQL Server after the current transaction is committed or rolled back by the programmer.

In order to use implicit transaction mode in SQL Server, first, we need to set the implicit transaction mode to ON using the SET IMPLICIT_TRANSACTIONS statement. The value for IMPLICIT_TRANSACTIONS can be ON or OFF. When the value for implicit transaction mode is set to ON then a new transaction is automatically started by SQL Server whenever we execute any SQL statement (Insert, Select, Delete, and Update).

I'll provide an example for clarification:

SET IMPLICIT_TRANSACTIONS ON

INSERT INTO Person VALUES (1, 'Nadim', 'Attar');
INSERT INTO Person VALUES (2, 'Belal', 'Attar');

COMMIT TRANSACTION

INSERT INTO Person VALUES (3, 'Hossam', 'Ekko');
UPDATE Person SET LastName = 'Ekko' WHERE Id = 2;
SELECT * FROM Person;        

When you execute the above statement and you will get the below data.

ROLLBACK TRANSACTION;        

Once you roll back the transaction, issue a select query against the person table and you will see the following data.

If you prefer not to use the implicit transaction mode, you can turn it off by using the following statement.

SET IMPLICIT_TRANSACTIONS OFF        

3- Explicit Transaction Mode in SQL Server:

In the Explicit mode of transaction, the developer is only responsible for beginning the transaction as well as ending the transaction. In other words, we can say that the transactions that have a START and END explicitly written by the programmer are called explicit transactions.


Here, every transaction should start with the BEGIN TRANSACTION statement and ends with either a ROLLBACK TRANSACTION statement (when the transaction does not complete successfully) or a COMMIT TRANSACTION statement (when the transaction completes successfully). The Explicit Transaction Mode is most commonly used in triggers, stored procedures, and application programs.

Explicit Transaction Mode Example using SQL Server Stored Procedure:

CREATE PROCEDURE SPAddPerson
AS
BEGIN
   BEGIN TRANSACTION
      INSERT INTO Person VALUES(3, 'Hossam', 'Ekko')
      INSERT INTO Person VALUES(4, 'Mothanna', 'Al Assar')
      IF(@@ERROR > 0)
      BEGIN
         ROLLBACK TRANSACTION
      END
      ELSE
      BEGIN
         COMMIT TRANSACTION
      END  
END        

In my next article, I'll talk about Nested Transactions in SQL Server using examples. For now, in this article, I'm explaining the different types of transactions (Auto Commit, Implicit, and Explicit) in SQL Server with examples. I hope you find this discussion on the various transaction types easy to understand and see the differences between Auto, Implicit, and Explicit modes in SQL Server.

要查看或添加评论,请登录

Nadim Attar的更多文章

  • Task.WhenEach

    Task.WhenEach

    Are you ready to take your asynchronous programming to the next level? With the release of .NET 9, we now have – a…

  • Exploring the Exciting New Features in C# 13

    Exploring the Exciting New Features in C# 13

    C# continues to evolve, making development more efficient and expressive. With the upcoming release of C# 13, several…

  • Understanding the IGNORE_DUP_KEY Feature in SQL Server

    Understanding the IGNORE_DUP_KEY Feature in SQL Server

    When working with databases, maintaining data integrity is critical. SQL Server offers various tools to ensure this…

  • C# Discriminated Unions (Dunet)

    C# Discriminated Unions (Dunet)

    Dunet is a simple source generator for discriminated unions in C#. This is the nuget of this library: https://www.

  • New keyed service dependency in .NET 8

    New keyed service dependency in .NET 8

    What’s a keyed service ? The "keyed" registration approach involves registering dependencies using both their type and…

  • HttpHandler

    HttpHandler

    After a long hiatus from posting articles, today I am presenting to you a great post discussing why we need to…

  • Dependency Injection Lifetimes in .Net Core

    Dependency Injection Lifetimes in .Net Core

    There are three lifetimes available with the Microsoft Dependency Injection container: transient, singleton, and…

  • Implementation of Dependency Injection Pattern in C#

    Implementation of Dependency Injection Pattern in C#

    Dependency Injection (DI) is a method in software design that helps us create code that's not too closely connected…

  • SOLID Principles

    SOLID Principles

    SOLID is an acronym for five design principles — Single Responsibility Principle (SRP), Open-Closed Principle (OCP)…

    2 条评论
  • FileZilla - The free FTP solution

    FileZilla - The free FTP solution

    FileZilla is a free, open source file transfer protocol (FTP) software tool that allows users to set up FTP servers or…

社区洞察