Tutorial Gateway

  • C
  • C#
  • Java
  • Python
  • SQL
  • MySQL
  • Js
  • BI Tools
    • Informatica
    • Talend
    • Tableau
    • Power BI
    • SSIS
    • SSRS
    • SSAS
    • MDX
    • R Tutorial
    • Alteryx
    • QlikView
  • More
    • C Programs
    • C++ Programs
    • Go Programs
    • Python Programs
    • Java Programs

SQL Transaction

by suresh

SQL Transaction is helpful to execute one more statement as a set. If a transaction 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 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
SQL Transaction 2

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

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

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

Placed Under: SQL

  • Install SQL Server
  • Install SQL Management Studio
  • Uninstall Management Studio
  • Install AdventureWorks Database
  • SQL Management Studio Intro
  • Connect SQL with sqlcmd utility
  • SQL Attach Database
  • SQL Detach Database
  • SQL Restore Database
  • Restore Database using BAK
  • SQL Rename Database with Files
  • Get SQL Database Names
  • SQL Create Table
  • SQL Rename Table
  • SQL Alter Table
  • SQL Add Column
  • SQL Rename Column
  • Get SQL Table Names in a DB
  • Find SQL Table Dependencies
  • Rename SQL Table & Column
  • SQL Global & Local Temp Table
  • SQL Table Variable
  • SQL Derived Table
  • SQL DATALENGTH
  • SQL Data Types
  • DML, DDL, DCL & TCL Cmds
  • SQL Query Builder
  • SQL ALIAS
  • SQL SELECT Statement
  • SQL SELECT DISTINCT
  • SQL SELECT INTO Statement
  • SQL INSERT Statement
  • SQL INSERT INTO SELECT
  • SQL BULK INSERT or BCP
  • SQL UPDATE Statement
  • SQL UPDATE from SELECT
  • SQL DELETE Statement
  • SQL TRUNCATE Table
  • SQL CASE Statement
  • SQL MERGE Statement
  • SQL Subquery
  • SQL CTE
  • SQL PIVOT
  • SQL UNPIVOT
  • SQL Clauses Examples
  • SQL TOP Clause
  • SQL WHERE Clause
  • SQL ORDER BY Clause
  • SQL GROUP BY Clause
  • SQL HAVING Clause
  • SQL Primary Key
  • SQL Foreign Key
  • SQL Referential Integrity
  • SQL Check Constraint
  • SQL Unique Constraint
  • SQL Default Constraint
  • SQL Clustered Index
  • SQL Non Clustered Index
  • SQL Filtered Indexes
  • SQL COALESCE Function
  • SQL IS NOT NULL
  • SQL IS NULL Function
  • SQL ISNULL
  • SQL JOINS
  • SQL CROSS JOIN
  • SQL FULL JOIN
  • SQL SELF JOIN
  • SQL Outer Joins
  • SQL Cross Join Vs Inner Join
  • SQL LEFT JOIN
  • SQL RIGHT JOIN
  • SQL AND & OR Operators
  • SQL Arithmetic Operators
  • SQL BETWEEN Operator
  • SQL Comparison Operators
  • SQL LIKE
  • SQL EXCEPT
  • SQL EXISTS Operator
  • SQL NOT EXISTS Operator
  • SQL INTERSECT
  • SQL IN Operator
  • SQL NOT IN Operator
  • SQL UNION
  • SQL UNION ALL
  • SQL IF ELSE
  • SQL ELSE IF
  • SQL WHILE LOOP
  • SQL Nested While Loop
  • SQL BREAK Statement
  • SQL CONTINUE Statement
  • SQL GOTO Statement
  • SQL IIF Function
  • SQL CHOOSE Function
  • SQL Change Data Capture
  • SQL Table Partitioning
  • SQL Table Partition using SSMS
  • SQL TRY CATCH
  • SQL VIEWS
  • SQL User Defined Functions
  • SQL Alter User Defined Functions
  • SQL Stored Procedure Intro
  • Useful System Stored Procedures
  • SQL SELECT Stored Procedure
  • SQL INSERT Stored Procedure
  • SQL UPDATE Stored Procedure
  • Stored Procedure Return Values
  • Stored Procedure Output Params
  • Stored Procedure Input Params
  • Insert SP result into Temp Table
  • SQL Triggers Introduction
  • SQL AFTER INSERT Triggers
  • SQL AFTER UPDATE Triggers
  • SQL AFTER DELETE Triggers
  • SQL INSTEAD OF INSERT
  • SQL INSTEAD OF UPDATE
  • SQL INSTEAD OF DELETE
  • SQL STATIC CURSOR
  • SQL DYNAMIC CURSOR
  • SQL FORWARD_ONLY Cursor
  • SQL FAST_FORWARD CURSOR
  • SQL KEYSET CURSOR
  • SQL TRANSACTIONS
  • SQL Nested Transactions
  • SQL ACID Properties
  • Create SQL Windows Login
  • Create SQL Server Login
  • SQL Server Login Error
  • Create SQL Server Roles
  • SQL Maintenance Plan
  • Backup SQL Database
  • SQL Ranking Functions Intro
  • SQL RANK Function
  • SQL PERCENT_RANK Function
  • SQL DENSE_RANK Function
  • SQL NTILE Function
  • SQL ROW_NUMBER
  • SQL Aggregate Functions
  • SQL Date Functions
  • SQL Mathematical Functions
  • SQL String Functions
  • SQL CAST Function
  • SQL TRY CAST
  • SQL CONVERT
  • SQL TRY CONVERT
  • SQL PARSE Function
  • SQL TRY_PARSE Function
  • SQL Calculate Running Total
  • SQL Find Nth Highest Salary
  • SQL Reverse String
  • SQL FOR XML PATH
  • SQL FOR XML AUTO
  • SQL FOR XML RAW

Copyright © 2021 · All Rights Reserved by Suresh

About Us | Contact Us | Privacy Policy