Master T SQL Transaction Commit Rollback Example Tutorial

Embarking on a journey to master T-SQL transactions? You've come to the right place! Understanding and implementing transactions, especially commit and rollback, is a vital aspect of database management. Let's dive into the world of T-SQL transactions, exploring commit and rollback operations with practical examples.

SQL Transactions Explained ๐Ÿ’พ
SQL Transactions Explained ๐Ÿ’พ

To begin, let's quickly refresh our understanding of T-SQL transactions. A transaction is a logical grouping of database operations that must all succeed or all fail. They're essential for maintaining data integrity and consistency. Now, let's devenit whether you've already noticed, our journey is structured around two primary areas: commit and rollback.

What is transaction in SQL?
What is transaction in SQL?

Understanding Commit in T-SQL

Simply put, a commit operation in T-SQL marks the point at which changes to the database are saved. Any transaction that hasn't been committed can be rolled back, essentially undoing any changes that were made. Let's explore this in more detail.

Transaction Management in DBMS Explained | ACID, States & Commands
Transaction Management in DBMS Explained | ACID, States & Commands

Consider the following example: ```sql BEGIN TRANSACTION; UPDATE Sales SET Quantity = Quantity + 1 WHERE ProductID = 10; COMMIT; ``` In this code snippet, the UPDATE statement modifies the database, but if an error were to occur, you'd want to revert back to the original state. That's where they introduce the concept of ' Commit. This keyword tells the database to save the changes.

Autocommit vs. Explicit Commit

๐Ÿ“š Transaction States in DBMS Explained | Active to Terminated (Simple Notes)
๐Ÿ“š Transaction States in DBMS Explained | Active to Terminated (Simple Notes)

T-SQL transactions aren't always explicit. By default, T-SQL uses 'autocommit', meaning that each statement is a separate, committed transaction. You saw an example of this earlier. If you execute an explicit commit within a transaction, like so: ```sql BEGIN TRANSACTION; UPDATE Sales ...; COMMIT; ``` The transaction is still autocommittable up until you execute another statement. It's only fully committed once a second statement is executed.

Now, let's consider a slightly more complex scenario: ```sql BEGIN TRANSACTION; UPDATE Products SET Price = Price * 1.1; -- Increase price by 10% UPDATE Sales SET Total = Quantity * 1.1; -- Increase sales by 10% COMMIT; ``` This example illustrates multiple operations working as one transaction. If the second update fails, you certainly wouldn't want the prices raised, would you? That's why using the commit statement is crucial.

Commit Example with Error Handling

the four different types of commands are shown in this graphic above it is an image of how to use them
the four different types of commands are shown in this graphic above it is an image of how to use them

Imagine you're processing an order, and an error occurs during the update. You shouldn't commit the transaction then, right? T-SQL provides error handling for such situations. Here's an example: ```sql BEGIN TRANSACTION; BEGIN TRY UPDATE Sales SET Quantity = Quantity + 1 WHERE ProductID = 10; END TRY BEGIN CATCH PRINT 'Error updating sales. Rolling back the transaction...'; ROLLBACK; END CATCH; COMMIT; ``` Here, the transaction rolls back the update operation once any error is captured within the BEGIN TRY and BEGIN CATCH.

The Art of Rollback in T-SQL

As we've already established, a T-SQL rollback relinquishes any changes made during a transaction. Understanding the rollback operation ensures data consistency in case of failure. Let's dive into this with examples.

All essential aspects of SQL server transaction
All essential aspects of SQL server transaction

Refer to the previously discussed examples above. If you replaced the 'commit' with 'rollback' at the end, you'd notice that the database reverts to its original state. Here's another example: ```sql BEGIN TRANSACTION; UPDATE Sales SET Quantity = Quantity + 100 WHERE ProductID = 10; -- Let's pretend an error occurs here, causing Quantity to increase by 10000 instead. ROLLBACK; ``` In this scenario, the database returns to its initial state, masking the fact an error occurred during the transaction.

Partial Rollback with SAVE TRANSACTION

Handling NULL in T-SQL
Handling NULL in T-SQL
SQL in 60 days
SQL in 60 days
SQL UPDATE Statement (Transact SQL) - Essential SQL
SQL UPDATE Statement (Transact SQL) - Essential SQL
an info poster showing the different types of web pages and how they are used to create them
an info poster showing the different types of web pages and how they are used to create them
Learn SQL Fast ๐Ÿš€ | Beginner SQL Commands Cheat Sheet for Data Analysts
Learn SQL Fast ๐Ÿš€ | Beginner SQL Commands Cheat Sheet for Data Analysts
2.4K views ยท 102 reactions | ๐ŸŽฏ SQL Cheatsheet โ€“ Everything You Need at a Glance Master SQL fundamentals with this clean and powerful SQL Cheatsheet ๐Ÿš€ Perfect for beginners, developers, data analysts, and inte | Codewithprashantt
2.4K views ยท 102 reactions | ๐ŸŽฏ SQL Cheatsheet โ€“ Everything You Need at a Glance Master SQL fundamentals with this clean and powerful SQL Cheatsheet ๐Ÿš€ Perfect for beginners, developers, data analysts, and inte | Codewithprashantt
four different types of soljoins with the names and numbers in each section on them
four different types of soljoins with the names and numbers in each section on them
DDL, DML, DCL & TCL Explained: SQL Language Categories Made Easy
DDL, DML, DCL & TCL Explained: SQL Language Categories Made Easy
๐Ÿ’ผ Most Asked SQL Interview Question!  โ“ Whatโ€™s the difference between DELETE, TRUNCATE & DROP? ๐Ÿšจ One keeps structure, one resets it, one wipes it out!  ๐Ÿ‘‰Preparing for interview? Check the Bio for playlist link  ๐Ÿ‘‰ Tag a friend who needs this! ๐Ÿ”–save it for your prep!  ๐Ÿ‘‰ HackerRank Topic wise SQL practice Questions: Link in Bio  Follow for daily data insights ๐Ÿ‘‡ ๐Ÿ“ธ Instagram | โ–ถ๏ธ YouTube | ๐Ÿ“˜ Facebook  . . . . . #sqlinterview #datascience #dataanalytics #sql #interviewprep #data #database #business... Interview Prep, How To Learn Sql For Data Science, Data Analyst, Computer Coding, Data Analysis Activities, Data Science Learning, Sql Programming, Job Advice, Sql Commands
๐Ÿ’ผ Most Asked SQL Interview Question! โ“ Whatโ€™s the difference between DELETE, TRUNCATE & DROP? ๐Ÿšจ One keeps structure, one resets it, one wipes it out! ๐Ÿ‘‰Preparing for interview? Check the Bio for playlist link ๐Ÿ‘‰ Tag a friend who needs this! ๐Ÿ”–save it for your prep! ๐Ÿ‘‰ HackerRank Topic wise SQL practice Questions: Link in Bio Follow for daily data insights ๐Ÿ‘‡ ๐Ÿ“ธ Instagram | โ–ถ๏ธ YouTube | ๐Ÿ“˜ Facebook . . . . . #sqlinterview #datascience #dataanalytics #sql #interviewprep #data #database #business... Interview Prep, How To Learn Sql For Data Science, Data Analyst, Computer Coding, Data Analysis Activities, Data Science Learning, Sql Programming, Job Advice, Sql Commands
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
SQL queries don
SQL queries don
an info sheet with different types of commands and instructions for using the webpages
an info sheet with different types of commands and instructions for using the webpages
SQL LEFT() Explained with Examples | Extract Characters from the Left in SQL Server
SQL LEFT() Explained with Examples | Extract Characters from the Left in SQL Server
Molelo de execuรงรฃo SQL
Molelo de execuรงรฃo SQL
SQL JOINS Made Easy ๐Ÿ”— | INNER, LEFT, RIGHT & FULL JOIN with Examples
SQL JOINS Made Easy ๐Ÿ”— | INNER, LEFT, RIGHT & FULL JOIN with Examples
SQL Joins Cheat Sheet
SQL Joins Cheat Sheet
a large poster with different types of food
a large poster with different types of food
SQL Cheatsheet In 2026 ๐Ÿš€
SQL Cheatsheet In 2026 ๐Ÿš€
the top 50 project ideas list is shown in orange and black, with text on it
the top 50 project ideas list is shown in orange and black, with text on it
a blue and white poster with the names of different types of letters on it's side
a blue and white poster with the names of different types of letters on it's side

Did you know that you can save the current state of a transaction to be able to revert to it later? That's what the 'SAVE TRANSACTION' command does. You can then use 'ROLLBACK TRANSACTION transaction_name' to rollback to that saved state. Here's how: ```sql BEGIN TRANSACTION; SAVE TRANSACTION update1; UPDATE Sales SET Quantity = Quantity + 100 WHERE ProductID = 10; SAVE TRANSACTION update2; UPDATE Sales SET Quantity = Quantity + 50 WHERE ProductID = 10; ``` Here, if you execute `ROLLBACK TRANSACTION update2` , the Quantities return to their pre-second update (pre-`update2`) values, not pre-first update (pre-`update1`) values.

A Common Rollback Scenario

A typical scenario where rollback is used is during testing - if something unexpected happens or an error occurs, you can quickly revert the database to its original state.

To conclude, understanding and effectively using the commit and rollback operations in T-SQL transactions is a fundamental aspect of database development. It enables you to maintain data integrity, consistency, and reliability within your systems. So go ahead, explore, experiment, and master the power of T-SQL transactions!

Related Articles

Create Temp Table Sql With Values Sql Create Table With Foreign Key With Name Sql Max Datetime Sql Max Date Group By W3 Sql Class Sql Create Table Foreign Key Example Pivot In Sql Server Management Studio Begin Transaction In Sql W3schools Begin Transaction Commit Rollback Sql Server Example Types Of Sql Statements