Sql Server Begin Commit And Rollback Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    6 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of SQL Server BEGIN, COMMIT, and ROLLBACK

SQL Server BEGIN, COMMIT, and ROLLBACK: A Detailed Guide

BEGIN TRANSACTION

The BEGIN TRANSACTION statement marks the start of a transaction block. It is used to begin a new transaction. Transactions can be nested, meaning a new transaction can begin before the previous one has been committed or rolled back. However, a nested transaction logically represents a single transaction block.

Syntax:

BEGIN TRANSACTION [transaction_name]

Example:

BEGIN TRANSACTION UpdateEmployeeSalaries

In the example above, UpdateEmployeeSalaries is the name of the transaction. Naming transactions is optional and primarily useful for debugging and managing nested transactions.

COMMIT TRANSACTION

The COMMIT TRANSACTION statement is used to save (commit) all the changes made within a transaction. When a transaction is committed, all operations within the transaction are permanently saved in the database, and other users can see the changes.

Syntax:

COMMIT TRANSACTION [transaction_name]

Example:

BEGIN TRANSACTION UpdateEmployeeSalaries

UPDATE Employees SET Salary = Salary + 5000 WHERE Department = 'Sales'

COMMIT TRANSACTION UpdateEmployeeSalaries

In the example above, the transaction named UpdateEmployeeSalaries increases the salary of all employees in the Sales department by 5000. If the COMMIT TRANSACTION statement is executed without any errors, the changes are saved to the database.

ROLLBACK TRANSACTION

The ROLLBACK TRANSACTION statement is used to undo all changes made within a transaction. Rolling back a transaction reverts the database to its state before the transaction began, ensuring that no partial updates are saved.

Syntax:

ROLLBACK TRANSACTION [transaction_name]

Example:

BEGIN TRANSACTION UpdateEmployeeSalaries

UPDATE Employees SET Salary = Salary + 5000 WHERE Department = 'Sales'

IF @@ERROR <> 0
BEGIN
    ROLLBACK TRANSACTION UpdateEmployeeSalaries
    PRINT 'Transaction rolled back due to error'
END
ELSE
BEGIN
    COMMIT TRANSACTION UpdateEmployeeSalaries
    PRINT 'Transaction committed successfully'
END

In this example, the transaction attempts to update the salaries of employees in the Sales department. If an error occurs (detected by checking the @@ERROR global variable), the transaction is rolled back using ROLLBACK TRANSACTION. Otherwise, the transaction is committed using COMMIT TRANSACTION.

Key Points to Remember

  1. Atomicity: All operations within a transaction are atomic. This means that either all operations succeed, or none do. If a transaction fails, the entire transaction is rolled back, and the database remains unchanged.

  2. Consistency: Transactions ensure that the database remains in a consistent state before and after their execution. A transaction cannot leave the database in an inconsistent state.

  3. Isolation: Transactions are isolated from each other, ensuring that operations within one transaction do not affect the operations in another. This is controlled by the transaction isolation levels in SQL Server.

  4. Durability: Once a transaction is committed, the changes are permanent and survive system failures.

  5. Nested Transactions: SQL Server supports nested transactions, meaning you can start a new transaction within a transaction. However, only the outermost transaction can be committed or rolled back. All nested transactions are logically part of the outermost transaction.

  6. Error Handling: Proper error handling is essential when working with transactions. Always ensure that you handle errors appropriately and roll back transactions when necessary to maintain database integrity.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement SQL Server BEGIN, COMMIT, and ROLLBACK

Understanding Transactions in SQL Server

A transaction in SQL Server is a group of one or more T-SQL statements that form a single unit of work. If all the T-SQL statements are successful, the transaction is committed. If any statement in the transaction fails, the transaction can be rolled back to its previous state.

The key commands are:

  • BEGIN TRANSACTION or BEGIN TRAN: Starts a new transaction.
  • COMMIT TRANSACTION or COMMIT TRAN: Commits the transaction, making all changes permanent.
  • ROLLBACK TRANSACTION or ROLLBACK TRAN: Rollbacks the transaction, undoing all changes made during the transaction.

Example Scenario

Let's use a simple example with a Products table to demonstrate the use of transactions.

Step 1: Create the Table

First, we need a table. Let's create a Products table with some initial data.

CREATE TABLE Products (
    ProductID INT PRIMARY KEY,
    ProductName NVARCHAR(100),
    Price DECIMAL(10, 2)
);

INSERT INTO Products (ProductID, ProductName, Price)
VALUES (1, 'Product A', 10.99),
       (2, 'Product B', 15.99),
       (3, 'Product C', 20.99);

SELECT * FROM Products;

Step 2: Begin a Transaction

We start a transaction using BEGIN TRANSACTION.

BEGIN TRANSACTION;

Step 3: Perform Some SQL Operations

Now let's perform some SQL operations within the transaction. For example, we update the price of Product A and insert a new product.

UPDATE Products SET Price = 12.99 WHERE ProductName = 'Product A';

INSERT INTO Products (ProductID, ProductName, Price)
VALUES (4, 'Product D', 25.99);

Step 4: Commit the Transaction

If everything is correct, we commit the transaction to make the changes permanent.

COMMIT TRANSACTION;

SELECT * FROM Products;

At this point, the changes are saved, and the Products table will show the updated price of Product A and the new Product D.

Step 5: Example with Rollback

Now let's see how rollback works. We'll start another transaction, make some changes, and then roll back.

BEGIN TRANSACTION;

-- Update Product B
UPDATE Products SET Price = 16.99 WHERE ProductName = 'Product B';

-- Insert Product E
INSERT INTO Products (ProductID, ProductName, Price)
VALUES (5, 'Product E', 30.99);

-- Rollback the transaction
ROLLBACK TRANSACTION;

After rollback, these changes are undone. When you select from Products, you will see that Product B's price and Product E's entry are not reflected.

SELECT * FROM Products;

Summary Example

Here is one more consolidated example to summarize all these points:

You May Like This Related .NET Topic

Login to post a comment.