Paramclasses Academy - Blog

Tutorials Details

←
Post 29 of 40
→

SQL Server Transactions Explained: BEGIN, COMMIT and ROLLBACK

SQL Server Transactions Explained: BEGIN, COMMIT and ROLLBACK

November 18, 2026

???? SQL Server Transactions Explained: BEGIN, COMMIT and ROLLBACK

???? Introduction

In Microsoft SQL Server, a Transaction is a logical unit of work that contains one or more SQL statements. It ensures that related database operations are completed successfully as a group or undone when something goes wrong.

For example, imagine transferring ₹5,000 from one bank account to another. The amount must be deducted from the sender's account and added to the receiver's account. If the deduction succeeds but the deposit fails, the database could become inconsistent.

SQL Server Transactions solve this problem using three important commands:

  • BEGIN TRANSACTION – Starts a transaction.

  • COMMIT TRANSACTION – Saves all changes permanently.

  • ROLLBACK TRANSACTION – Cancels changes made within the transaction.

In this tutorial by Param Classes, you will learn how transactions work, understand ACID properties, and practice transaction management using real-world SQL Server examples.

???? What You Will Learn

  1. What is a SQL Server Transaction?

  2. Why are transactions important?

  3. Understanding ACID properties.

  4. Types of SQL Server transactions.

  5. How to use BEGIN TRANSACTION.

  6. How to use COMMIT TRANSACTION.

  7. How to use ROLLBACK TRANSACTION.

  8. Practical bank transfer example.

  9. Using TRY...CATCH with transactions.

  10. Understanding SAVE TRANSACTION and savepoints.

  11. Checking transaction status using @@TRANCOUNT.

  12. SQL Server transaction best practices.


1️⃣ What Is a Transaction in SQL Server?

A Transaction is a group of one or more database operations treated as a single logical unit of work.

If all operations complete successfully, SQL Server can commit the transaction. If an error occurs and the transaction must be canceled, it can be rolled back.

Example:

Consider a bank transfer:

  1. Deduct ₹5,000 from Account A.

  2. Add ₹5,000 to Account B.

  3. Save both operations together.

If the second operation fails, the first operation should also be canceled. This prevents money from being deducted without being credited to the receiver.

Basic Transaction Syntax

BEGIN TRANSACTION;

-- SQL statements
INSERT INTO TableName
VALUES (...);

UPDATE TableName
SET ColumnName = Value;

COMMIT TRANSACTION;

If you need to cancel the transaction, use:

ROLLBACK TRANSACTION;

Important: A transaction remains active until it is committed, rolled back, or otherwise ended by SQL Server. Always make sure that an explicit transaction is properly completed.


2️⃣ Why Are Transactions Important?

Transactions are important because they help maintain database consistency and protect related operations from being partially completed.

Major Benefits:

  • Data Consistency: Helps maintain correct and reliable database records.

  • Error Handling: Allows changes to be canceled when an operation fails.

  • Data Integrity: Keeps related database operations together.

  • Reliability: Helps protect important business operations.

  • Controlled Updates: Makes multiple INSERT, UPDATE, and DELETE operations part of one unit of work.

Real-World Applications:

  • Banking and money transfers.

  • Online shopping and order processing.

  • Inventory management.

  • Railway and airline booking systems.

  • Payment processing.

  • Student fee management systems.


3️⃣ Understanding ACID Properties

SQL Server transactions follow the important database principles known as ACID properties.

ACID stands for:

  • Atomicity

  • Consistency

  • Isolation

  • Durability

A. Atomicity

Atomicity means that a transaction is treated as one complete unit.

Either all required operations are committed, or the transaction is rolled back.

Example: In a bank transfer, both the debit and credit operations should succeed together.

B. Consistency

Consistency means that a transaction should move the database from one valid state to another valid state, maintaining applicable rules and constraints.

Example: A bank account balance should not become invalid because of an incomplete transaction.

C. Isolation

Isolation controls how concurrent transactions interact with each other.

It helps prevent one transaction from incorrectly interfering with another transaction.

SQL Server provides transaction isolation levels such as:

  • READ UNCOMMITTED

  • READ COMMITTED

  • REPEATABLE READ

  • SNAPSHOT

  • SERIALIZABLE

D. Durability

Durability means that once a transaction is successfully committed, its changes are preserved as part of the database.

Example: After a successful bank transfer is committed, the updated account balances are saved.

ACID Properties Summary

Property Meaning
Atomicity All operations succeed or are rolled back
Consistency Database rules remain satisfied
Isolation Concurrent transactions are controlled
Durability Committed changes are preserved

4️⃣ Types of Transactions in SQL Server

SQL Server supports different transaction modes.

A. Autocommit Transactions

Autocommit is the default transaction mode in SQL Server.

Each individual statement runs as its own transaction and is automatically committed if successful.

Example:

INSERT INTO Employees
(EmployeeName, Salary)
VALUES
('Rahul Sharma', 35000);

If the statement succeeds, SQL Server automatically commits it when autocommit mode is active.

B. Explicit Transactions

An explicit transaction is started and completed manually using transaction statements.

Example:

BEGIN TRANSACTION;

UPDATE Employees
SET Salary = 40000
WHERE EmployeeID = 1;

COMMIT TRANSACTION;

Here, the developer controls when the transaction starts and finishes.

C. Implicit Transactions

When implicit transaction mode is enabled, SQL Server automatically starts a transaction when certain statements are executed. The application or developer must explicitly commit or roll back the transaction.

Example:

SET IMPLICIT_TRANSACTIONS ON;

UPDATE Employees
SET Salary = 45000
WHERE EmployeeID = 1;

COMMIT TRANSACTION;

SET IMPLICIT_TRANSACTIONS OFF;

Note: Always complete an implicit transaction with COMMIT or ROLLBACK before leaving the session or changing transaction mode.


5️⃣ What Is BEGIN TRANSACTION?

BEGIN TRANSACTION marks the starting point of an explicit transaction.

After this statement, the following database modifications belong to that transaction until it is committed or rolled back.

Syntax

BEGIN TRANSACTION;

-- SQL operations

Practical Example

BEGIN TRANSACTION;

UPDATE Employees
SET Salary = 50000
WHERE EmployeeID = 1;

SELECT *
FROM Employees
WHERE EmployeeID = 1;

COMMIT TRANSACTION;

Explanation:

  1. BEGIN TRANSACTION starts the transaction.

  2. UPDATE changes the employee salary.

  3. SELECT displays the updated record.

  4. COMMIT TRANSACTION saves the change.

Remember: A SELECT statement can be used to inspect data during a transaction, but it does not itself commit the transaction.


6️⃣ What Is COMMIT TRANSACTION?

COMMIT TRANSACTION successfully completes an active transaction and makes its database modifications permanent.

Once a transaction has been committed, you cannot use ROLLBACK to undo that completed transaction.

Syntax

COMMIT TRANSACTION;

Practical Example

BEGIN TRANSACTION;

INSERT INTO Employees
(EmployeeName, Salary)
VALUES
('Priya Verma', 42000);

COMMIT TRANSACTION;

Explanation:

  • The transaction starts.

  • A new employee record is inserted.

  • COMMIT TRANSACTION saves the inserted record.

Check the result:

SELECT *
FROM Employees
WHERE EmployeeName = 'Priya Verma';

The inserted record is now committed.


7️⃣ What Is ROLLBACK TRANSACTION?

ROLLBACK TRANSACTION cancels the changes made during an active transaction and returns the database to its state at the beginning of that transaction or to a specified savepoint.

Syntax

ROLLBACK TRANSACTION;

Practical Example

BEGIN TRANSACTION;

UPDATE Employees
SET Salary = 90000
WHERE EmployeeID = 1;

ROLLBACK TRANSACTION;

Check the employee record:

SELECT *
FROM Employees
WHERE EmployeeID = 1;

The salary update is canceled because the transaction was rolled back.

Important: ROLLBACK does not undo changes that were already committed in an earlier transaction.


8️⃣ Difference Between BEGIN, COMMIT and ROLLBACK

Command Purpose Result
BEGIN TRANSACTION Starts a transaction Opens a transaction
COMMIT TRANSACTION Completes a transaction successfully Saves modifications
ROLLBACK TRANSACTION Cancels a transaction Undoes transaction modifications

Easy Way to Remember:

  • BEGIN = Start

  • COMMIT = Save

  • ROLLBACK = Undo


9️⃣ Practical SQL Server Transaction Example: Bank Transfer

Now let's create a real-world bank transfer example using SQL Server.

Suppose we have two bank accounts:

  • Account 101 has ₹20,000.

  • Account 102 has ₹10,000.

We want to transfer ₹5,000 from Account 101 to Account 102.

Step 1: Create the BankAccounts Table

CREATE TABLE BankAccounts
(
    AccountID INT PRIMARY KEY,
    AccountHolder VARCHAR(100),
    Balance DECIMAL(12,2)
);
GO

Step 2: Insert Sample Records

INSERT INTO BankAccounts
(AccountID, AccountHolder, Balance)
VALUES
(101, 'Rahul Sharma', 20000),
(102, 'Priya Verma', 10000);
GO

Step 3: Check Initial Account Balances

SELECT *
FROM BankAccounts;

Initial Account Balances:

AccountID AccountHolder Balance
101 Rahul Sharma 20000.00
102 Priya Verma 10000.00

Step 4: Start the Transaction

BEGIN TRANSACTION;

Step 5: Deduct Money From the Sender

UPDATE BankAccounts
SET Balance = Balance - 5000
WHERE AccountID = 101;

Step 6: Add Money to the Receiver

UPDATE BankAccounts
SET Balance = Balance + 5000
WHERE AccountID = 102;

Step 7: Commit the Transaction

COMMIT TRANSACTION;

Step 8: Check Updated Balances

SELECT *
FROM BankAccounts;

Expected Result:

AccountID AccountHolder Balance
101 Rahul Sharma 15000.00
102 Priya Verma 15000.00

The ₹5,000 has been deducted from Rahul's account and credited to Priya's account.

Practical Learning: Both balance modifications are committed as part of one transaction.


???? Practical Example: Rollback a Bank Transaction

Now suppose an error occurs after deducting money from the sender but before completing the transfer.

We can roll back the transaction to cancel the deduction.

BEGIN TRANSACTION;

UPDATE BankAccounts
SET Balance = Balance - 3000
WHERE AccountID = 101;

-- Cancel the transaction
ROLLBACK TRANSACTION;

Check the balances:

SELECT *
FROM BankAccounts;

The account balance will remain unchanged from its state before this transaction.

Important: This example demonstrates how ROLLBACK prevents an incomplete operation from leaving the database with only one side of the intended change.


1️⃣1️⃣ Using TRY...CATCH with Transactions

In real-world applications, database operations can fail because of invalid data, constraint violations, insufficient balances, or other errors.

SQL Server provides TRY...CATCH for error handling.

  • TRY: Contains the SQL statements that may generate errors.

  • CATCH: Handles errors raised inside the TRY block.

Practical Bank Transfer With Error Handling

SET XACT_ABORT ON;

BEGIN TRY

    BEGIN TRANSACTION;

    DECLARE @Amount DECIMAL(12,2) = 5000;
    DECLARE @SenderBalance DECIMAL(12,2);

    SELECT @SenderBalance = Balance
    FROM BankAccounts
    WHERE AccountID = 101;

    IF @SenderBalance IS NULL
        THROW 50001, 'Sender account not found.', 1;

    IF NOT EXISTS
    (
        SELECT 1
        FROM BankAccounts
        WHERE AccountID = 102
    )
        THROW 50002, 'Receiver account not found.', 1;

    IF @SenderBalance < @Amount
        THROW 50003, 'Insufficient account balance.', 1;

    UPDATE BankAccounts
    SET Balance = Balance - @Amount
    WHERE AccountID = 101;

    UPDATE BankAccounts
    SET Balance = Balance + @Amount
    WHERE AccountID = 102;

    COMMIT TRANSACTION;

    PRINT 'Transaction completed successfully.';

END TRY

BEGIN CATCH

    IF XACT_STATE() <> 0
        ROLLBACK TRANSACTION;

    PRINT ERROR_MESSAGE();

END CATCH;

Explanation:

  1. SET XACT_ABORT ON helps ensure that many run-time errors terminate and roll back the transaction.

  2. TRY contains the transaction operations.

  3. The sender account is checked.

  4. The receiver account is checked.

  5. The sender's balance is checked before transferring money.

  6. Both account balances are updated.

  7. COMMIT saves the transaction if everything succeeds.

  8. CATCH handles errors and rolls back an active or uncommittable transaction.

  9. ERROR_MESSAGE() displays the error message.

  10. XACT_STATE() helps determine the current transaction state.

Important: This is an educational example. A production banking application also needs appropriate concurrency control and safeguards against simultaneous transfers.


1️⃣2️⃣ What Is SAVE TRANSACTION?

SAVE TRANSACTION creates a savepoint inside an active transaction.

A savepoint allows you to roll back part of a transaction without necessarily canceling all the operations performed since the transaction began.

Syntax

SAVE TRANSACTION SavePointName;

Practical Example

BEGIN TRANSACTION;

UPDATE BankAccounts
SET Balance = Balance - 1000
WHERE AccountID = 101;

SAVE TRANSACTION TransferPoint;

UPDATE BankAccounts
SET Balance = Balance + 1000
WHERE AccountID = 102;

-- Roll back only to the savepoint
ROLLBACK TRANSACTION TransferPoint;

-- Complete the outer transaction
COMMIT TRANSACTION;

Explanation:

  • BEGIN TRANSACTION starts the transaction.

  • The first UPDATE deducts ₹1,000.

  • SAVE TRANSACTION creates a savepoint.

  • The second UPDATE adds ₹1,000.

  • ROLLBACK TRANSACTION TransferPoint undoes changes made after the savepoint.

  • COMMIT TRANSACTION commits the remaining transaction.

Important: A savepoint is not an independent transaction. Rolling back to it does not end the outer transaction. Savepoints are also subject to SQL Server's transaction and distributed transaction limitations.


1️⃣3️⃣ What Is @@TRANCOUNT in SQL Server?

@@TRANCOUNT is a SQL Server system function that returns the number of active transaction levels in the current session.

Example

SELECT @@TRANCOUNT AS TransactionCount;

Before starting a transaction, the result is normally:

TransactionCount
0

Start a transaction:

BEGIN TRANSACTION;

SELECT @@TRANCOUNT AS TransactionCount;

Result:

TransactionCount
1

Commit the transaction:

COMMIT TRANSACTION;

SELECT @@TRANCOUNT AS TransactionCount;

Result:

TransactionCount
0

Remember:

  • BEGIN TRANSACTION increases @@TRANCOUNT.

  • COMMIT TRANSACTION decreases it by one.

  • A full ROLLBACK TRANSACTION resets it to zero.

Important: SQL Server does not support independently manageable nested transactions. An inner COMMIT only decreases the transaction count; it does not permanently commit the work independently of the outer transaction.


1️⃣4️⃣ Difference Between COMMIT and ROLLBACK

Feature COMMIT ROLLBACK
Purpose Save changes Cancel changes
Database Changes Preserved Undone
Transaction Successfully completed Canceled
Can Undo Later? Not through that completed transaction Changes are already canceled
Common Use Successful operations Error or cancellation

1️⃣5️⃣ SQL Server Transaction Best Practices

Follow these practices when using transactions in professional database applications.

1. Keep Transactions Short

Avoid keeping transactions open for a long time. Long-running transactions can hold locks and affect other database operations.

2. Use TRY...CATCH

Handle errors properly and make sure active transactions are completed or rolled back.

3. Validate Data Before Modification

Check account balances, required records, and other business conditions before performing critical updates.

4. Use COMMIT and ROLLBACK Carefully

Every explicit transaction should have a clear success and failure path.

5. Avoid Unnecessary Transactions

Use transactions when multiple related database operations need to succeed or fail together.

6. Understand Isolation Levels

Choose appropriate isolation levels based on the application's concurrency and consistency requirements.

7. Monitor Active Transactions

Use transaction-related system information and monitoring tools to identify long-running or uncommitted transactions.

8. Test Error Scenarios

Test successful operations, invalid inputs, missing records, and other failure conditions.


1️⃣6️⃣ Frequently Asked Questions (FAQs)

Q1. What is a Transaction in SQL Server?

A transaction is a logical unit of work containing one or more SQL statements that are managed together.

Q2. What is BEGIN TRANSACTION?

BEGIN TRANSACTION starts an explicit transaction in SQL Server.

Q3. What is COMMIT TRANSACTION?

COMMIT TRANSACTION successfully completes an active transaction and saves its modifications.

Q4. What is ROLLBACK TRANSACTION?

ROLLBACK TRANSACTION cancels changes made within an active transaction or rolls back to a specified savepoint.

Q5. What are ACID properties?

ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties describe important transaction guarantees.

Q6. What happens if an error occurs during a transaction?

The transaction may need to be rolled back. TRY...CATCH and XACT_STATE() can help handle transaction errors safely.

Q7. What is the difference between COMMIT and ROLLBACK?

COMMIT saves transaction changes, whereas ROLLBACK cancels them.

Q8. What is SAVE TRANSACTION?

SAVE TRANSACTION creates a savepoint inside an active transaction, allowing a partial rollback.

Q9. What is @@TRANCOUNT?

@@TRANCOUNT returns the current transaction nesting count for the session.

Q10. Are transactions useful in banking applications?

Yes. Transactions are essential for operations such as money transfers, where related account updates must be handled together.


???? Conclusion

SQL Server Transactions are essential for maintaining reliable and consistent database operations. By using BEGIN TRANSACTION, COMMIT TRANSACTION, and ROLLBACK TRANSACTION, developers can manage multiple database operations as a single unit of work.

In this tutorial, we explored ACID properties, transaction modes, bank transfer examples, TRY...CATCH error handling, SAVE TRANSACTION, and @@TRANCOUNT.

Understanding these concepts will help you develop reliable database applications for banking, e-commerce, inventory management, and other real-world systems.

At Param Classes, we focus on practical programming and database tutorials that help students understand concepts through step-by-step examples and hands-on learning.

Keep learning, keep practicing, and improve your SQL Server skills with Param Classes!

←
Post 29 of 40
→