What is SQL Transaction

SQL Server Transaction is helpful for executing one more statement as a set. If it is successful, all the changes made in that transaction will apply to the table. If any single statement inside the transaction encounters an error, then changes made in that transaction will be erased or rolled back.

Let me show you the list of various examples that can explain Transactions. They are BEGIN TRANSACTION, COMMIT, ROLLBACK, named, Trans inside the IF ELSE, and SQL Server Transactions inside the TRY CATCH block. List of things to remember while working on the Transactions.

  • Every trans should start with BEGIN TRANSACTION, BEGIN TRAN, or BEGIN TRANSACTION Transaction_Name
  • Every Transaction in SQL Server must end with either COMMIT or ROLLBACK statements.
  • COMMIT TRANSACTION: This statement tells the server to save the changes made between the BEGIN and COMMIT. There are multiple ways to write this statement. Either you can write COMMIT, COMMIT TRAN, COMMIT TRANSACTION, or COMMIT TRANSACTION Transaction_Name
  • ROLLBACK TRANSACTION: This statement tells the Server to erase all the changes made between the BEGIN and ROLLBACK. There are multiple ways to write this statement. Either you can write ROLLBACK, ROLLBACK TRAN, ROLLBACK TRANSACTION, or ROLLBACK TRANSACTION Transaction_Name

SQL Server Transaction Example

In this example, we will place an INSERT INTO SELECT statement inside the BEGIN and COMMIT transaction. As you can see, it will select the top four records from the Employee table and store them in the Employee Records table.

BEGIN TRAN

INSERT INTO [dbo].[EmployeeRecords] (
	         [EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
SELECT TOP 4 [EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales]
FROM [dbo].[Employee]

COMMIT TRANSACTION

Run the above query

Messages
--------
(4 row(s) affected)

Let us see the inserted rows in the Employee Records table.

Employee Records 3

Transaction in the SQL server is not limited to a single statement. We can place multiple statements inside one trans. In this SQL Server example, we will put one Insert Statement and Update Statement.

BEGIN TRANSACTION

INSERT INTO [dbo].[EmployeeRecords] (
	    [EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
     VALUES (5, 'SQL', 'Server', 'Education', 'Teaching', 10000, 200)

UPDATE [dbo].[EmployeeRecords]
	SET [Education] = 'Tutorials',
		[YearlyIncome] = 98000
	WHERE [EmpID] = 5
	   
COMMIT TRANSACTION

Run the Insert and Update statements in a single query

Messages
--------
(1 row(s) affected)
(1 row(s) affected)

The records are in the Employee table after that.

SQL Transaction 5

Auto Rollback in SQL Server Transaction

The statements inside a transaction are executed as a set, and if one statement fails, then the remaining statements with not execute. This process is also called Auto Rollback transactions.

This time we will deliberately fail one statement inside the Transaction. As you can see, the update statement will return an error because we are entering the string (VARCHAR) information into the float data type.

BEGIN TRANSACTION

INSERT INTO [dbo].[EmployeeRecords] (
	    [EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
     VALUES (6, 'Tutorial', 'Gateway', 'Education', 'Learning', 65000, 1400)

UPDATE [dbo].[EmployeeRecords]
	SET [Education] = 'Masters',
	    [YearlyIncome] = 'Wrong Data'
	WHERE [EmpID] = 6
	   
COMMIT TRANSACTION
Error Message 8114. Converting Data Type 6

Though, there is an error in the Update statement. We cannot see the inserted record because the transaction is rolled back.

AUTO ROLLBACK SQL Transaction 7

Let me remove the BEGIN and COMMIT from the above code snippet and execute the statements.

INSERT INTO [dbo].[EmployeeRecords] (
	         [EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
     VALUES (6, 'Tutorial', 'Gateway', 'Education', 'Learning', 65000, 1400)

UPDATE [dbo].[EmployeeRecords]
	SET [Education] = 'Masters',
		[YearlyIncome] = 'Wrong Data'
	WHERE [EmpID] = 6
Insert Statement Failed and Rollback happens on Table 8

I have inserted the new record of Emp Id 6 but failed to update it.

Table records 9

Rollback Transaction in SQL Server

Rollback is useful to roll back to either the beginning of the transaction or to the save point. You can use this SQL Rollback to remove the half-completed rows or to handle errors.

For example, if your transaction is inserting a new record and throws an error, then you can use this rollback to revert the table to the original position.

In this example, we will insert a new record into the Employee table and apply the rollback transaction after the insert. To demonstrate this, we are using Select Statement inside and outside of the transaction. The first select statement will show you the table records before completing the transaction.

BEGIN TRANSACTION

INSERT INTO [dbo].[EmployeeRecords] (
	         [EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
     VALUES (7, 'SQL Server', 'Tutorial', 'Masters', 'Learn', 55000, 1250)

SELECT * FROM [dbo].[EmployeeRecords]

ROLLBACK TRANSACTION

SELECT * FROM [dbo].[EmployeeRecords]

Though there is no error in the above statement, it has not inserted the record.

SQL Transaction 10

Named Transactions in SQL Server

It allows you to name your transaction. When you are working with multiple trans in one query, it is always advisable to use the named transaction.

-- AddEmployee is the Transaction name
BEGIN TRANSACTION AddEmployee

INSERT INTO [dbo].[EmployeeRecords] (
	    [EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
     VALUES (7, 'SQL Server', 'Tutorial', 'Masters', 'Learn', 55000, 1250)

COMMIT TRANSACTION AddEmployee

SELECT * FROM [dbo].[EmployeeRecords]
Named SQL Transaction 11

Transaction in IF ELSE statement

The Transactions are much more useful if we place them inside any conditional statements such as IF ELSE. For instance, check for the existing records in the employee table before the insertion, and if it is there, rollback, else commit, etc.

The below statement is a simple SQL Server Transactions example, where we declared a variable (assuming the user will enter the value). Next, we used the insert statement, next within the If we are checking whether the @sales is less than 1000 or not. If it is true, ROLLBACK the transaction otherwise, Commit it in the Select statement.

DECLARE @Sales FLOAT = 250.0

BEGIN TRANSACTION AddEmployee

INSERT INTO [dbo].[EmployeeRecords] (
	    [EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
     VALUES (8, 'Dave', 'Rob', 'High School', 'Professional', 85000, @Sales)

IF @Sales < 1000
	BEGIN
	    ROLLBACK TRANSACTION AddEmployee
	    PRINT 'Sorry! Sales Amount Should be More than 1000'
	END
ELSE
	BEGIN
		COMMIT TRANSACTION AddEmployee
		PRINT 'Inserted the Record Successfully'
	END		
SELECT * FROM [dbo].[EmployeeRecords]
SQL Transaction IF ELSE 12

Let me show you the records

After Insert Into 13

This time we changed the variable @Sales value to 1450.02

DECLARE @Sales FLOAT = 1450.02

BEGIN TRANSACTION AddEmployee

INSERT INTO [dbo].[EmployeeRecords] (
	    [EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
     VALUES (8, 'Dave', 'Rob', 'High School', 'Professional', 85000, @Sales)

IF @Sales < 1000
	BEGIN
	    ROLLBACK TRANSACTION AddEmployee
	    PRINT 'Sorry! Sales Amount Should be More than 1000'
	END
ELSE
	BEGIN
		COMMIT TRANSACTION AddEmployee
		PRINT 'Inserted the Record Successfully'
	END		
SELECT * FROM [dbo].[EmployeeRecords]
SQL Transaction 14

The result data is in the employee table.

Employee records 15

SQL Transaction in TRY CATCH

Transactions are very useful if we place them inside the TRY CATCH block. For instance, if there is an error inside it, then you can use the catch block to roll back the transaction to the original position.

It is a simple Transactions example, where we placed one select and one update statement inside the Try Catch block. If you observe closely, our update statement will throw an error because of data type conflict.

BEGIN TRY
	BEGIN TRANSACTION AddEmployee

	INSERT INTO [dbo].[EmployeeRecords] (
			[EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
		 VALUES (9, 'Chong', 'Lee', 'Tutorials', 'Developer', 66500, 1950)

	UPDATE [dbo].[EmployeeRecords]
		SET [Education] = 'Bachelors',
		    [YearlyIncome] = 'Hey You gotme Wrong!'
		WHERE [EmpID] = 9

	COMMIT TRANSACTION AddEmployee
	PRINT 'Inserted the Record Successfully'
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION AddEmployee
	PRINT 'Sorry! There is a Data Type Mismatch for yearly Income'
END CATCH
	
SELECT * FROM [dbo].[EmployeeRecords]
SQL Transaction Try Catch 16

and the data inside the table is:

Data inside a Table 17

Let me change the yearly income value to 91567 and run it

BEGIN TRY
	BEGIN TRANSACTION AddEmployee

	INSERT INTO [dbo].[EmployeeRecords] (
				 [EmpID], [FirstName], [LastName], [Education], [Occupation], [YearlyIncome], [Sales])
		 VALUES (9, 'Chong', 'Lee', 'Tutorials', 'Developer', 66500, 1950)

	UPDATE [dbo].[EmployeeRecords]
		SET [Education] = 'Bachelors',
			[YearlyIncome] = 91567 -- We changed it
		WHERE [EmpID] = 9

	COMMIT TRANSACTION AddEmployee
	PRINT 'Inserted the Record Successfully'
END TRY
BEGIN CATCH
	ROLLBACK TRANSACTION AddEmployee
		PRINT 'Sorry! There is a Data Type Mismatch for yearly Income'
END CATCH
	
SELECT * FROM [dbo].[EmployeeRecords]
SQL Transaction 18

and the data inside the Employee table is:

After Update records 19

Common Mistakes

One of the common mistakes that will happen while using these in a query. As you can see, we are using a simple Update statement after the SQL BEGIN TRANSACTION but forgot to mention COMMIT or ROLLBACK.

BEGIN TRANSACTION 
	UPDATE [dbo].[EmployeeRecords]
		SET [YearlyIncome] = 125896
		   WHERE [EmpID] = 6
Messages
--------
(1 row(s) affected)

Let me open one more query window (click New query in SSMS) and write a simple select statement to select all the records in the Employee Records table.

See, the execution is taking longer than usual. It is because, by default, the Select statement will return the committed data, and we forgot to commit the update.

Common Update Statement Mistakes Rollback 21

Let me set the Transaction Isolation level to Read Uncommitted. It will read the uncommitted data.

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT * FROM [dbo].[EmployeeRecords]
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED 22