What is SQL Transaction

SQL Transaction is helpful to execute one more statement as a set. If a transaction is successful, all the changes made in that SQL 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 the SQL Transaction. They are BEGIN TRANSACTION, COMMIT TRANSACTION, ROLLBACK TRANSACTION, named transactions, Transactions inside the IF ELSE, and SQL Server Transactions inside the TRY CATCH block. List of things to remember while working on the SQL server Transactions.

  • Every SQL transaction 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 SQL 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 SQL 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 Transaction Example

In this SQL Server transactions 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.

--SQL Server Transaction Example
USE [SQL Tutorial]
GO

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 transactions query

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

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

SQL Transaction 3

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

--SQL Server Transaction Example
USE [SQL Tutorial]
GO

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 thee Insert and Update statements in single transaction query

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

The records in the Employee table after that transaction.

SQL Transaction 5

Auto Rollback in SQL Transaction

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

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.

--SQL Server Transaction Example
USE [SQL Tutorial]
GO

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
SQL Transaction 6

Though, there is an error at Update statement. We are unable to see the inserted record because it is rolled back by the SQL.

SQL Transaction 7

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

--SQL Server Transaction Example
USE [SQL Tutorial]
GO

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
SQL Transaction 8

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

SQL Transaction 9

Rollback Transaction in SQL Server

Rollback transaction in SQL is useful to roll back transactions 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 it throws an error, then you can use this rollback transaction 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 a Transaction, and outside the transaction. The first select statement will show you the table records before the transaction completed.

--SQL Server Transaction Example
USE [SQL Tutorial]
GO

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

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

--SQL Server Transaction Example
USE [SQL Tutorial]
GO
-- 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]
SQL Transaction 11

SQL Transaction in IF ELSE statement

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

The below statement is a simple SQL Server Transactions example, where we declared a variable (assuming user going to 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 the transaction in Select statement.

--SQL Server Transaction Example
USE [SQL Tutorial]
GO
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 12

Let me show you the records

SQL Transaction 13

This time we changed the variable @Sales value to 1450.02

--SQL Server Transaction Example
USE [SQL Tutorial]
GO
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 in the employee table.

SQL Transaction 15

SQL Transaction in TRY CATCH

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

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

--SQL Server Transaction Example
USE [SQL Tutorial]
GO
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 16

and the data inside the table is:

SQL Transaction 17

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

--SQL Server Transaction Example
USE [SQL Tutorial]
GO
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:

SQL Transaction 19

SQL Transaction Common Mistake

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

--SQL Server Transaction Example
USE [SQL Tutorial]
GO

BEGIN TRANSACTION 
	UPDATE [dbo].[EmployeeRecords]
		SET [YearlyIncome] = 125896
		   WHERE [EmpID] = 6

Execute the Query

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.

SQL Transaction 21

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

--SQL Server Transaction Example
USE [SQL Tutorial]
GO
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SELECT * FROM [dbo].[EmployeeRecords]
SQL Transaction 22