The Wayback Machine - https://web.archive.org/web/20240908131846/https://www.geeksforgeeks.org/sql-transactions/
Open In App

SQL TRANSACTIONS

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Transactions group a set of tasks into a single execution unit. Each transaction begins with a specific job and ends when all the tasks in the group successfully completed. If any of the tasks fail, the transaction fails. Therefore, a transaction has only two results: success or failure.

Example of a transaction to transfer $150 from account A to account B:

1. read(A)
2. A:= A – 150
3. write(A)
4. read(B)
5. B:= B + 150
6. write(B)

Incomplete steps result in the failure of the transaction. A database transaction, by definition, must be atomic, consistent, isolated, and durable. 
These are popularly known as ACID properties.  These properties can ensure the concurrent execution of multiple transactions without conflict.

Properties of Transaction

  • Atomicity: The outcome of a transaction can either be completely successful or completely unsuccessful. The whole transaction must be rolled back if one part of it fails.
  • Consistency: Transactions maintain integrity restrictions by moving the database from one valid state to another.
  • Isolation: Concurrent transactions are isolated from one another, assuring the accuracy of the data.
  • Durability: Once a transaction is committed, its modifications remain in effect even in the event of a system failure.

How to Implement Transactions Control Command using SQL?

The following commands are used to control transactions. It is important to note that these statements cannot be used while creating tables and are only used with the DML Commands such as- INSERT, UPDATE, and DELETE. 

BEGIN TRANSACTION Command

It indicates the start point of an explicit or local transaction. 

Syntax:

BEGIN TRANSACTION transaction_name ;

SET TRANSACTION Command

The values for the properties of the current transaction, such as the transaction isolation level and access mode, are set using the SET TRANSACTION Statement in MySQL.

Syntax: 

SET TRANSACTION [ READ WRITE | READ ONLY ];

COMMIT Command

If everything is in order with all statements within a single transaction, all changes are recorded together in the database is called committed. The COMMIT command saves all the transactions to the database since the last COMMIT or ROLLBACK command. 

Syntax:

COMMIT;

Example:

Sample Table1 

output

output

Following is an example which would delete those records from the table which have age = 20 and then COMMIT the changes in the database. 

Query 

DELETE FROM Student WHERE AGE = 20;
COMMIT;

Output

Thus, two rows from the table would be deleted and the SELECT statement would look like, 

output

output

ROLLBACK Command

If any error occurs with any of the SQL grouped statements, all changes need to be aborted. The process of reversing changes is called rollback. This command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued. 

Syntax for ROLLBACK command: 

ROLLBACK;

Example:

From the above example Sample table1, 
Delete those records from the table which have age = 20 and then ROLLBACK the changes in the database. 

Query 

DELETE FROM Student WHERE AGE = 20;
ROLLBACK;

Output

output

output

SAVEPOINT Command

SAVEPOINT creates points within the groups of transactions in which to ROLLBACK. 
A SAVEPOINT is a point in a transaction in which you can roll the transaction back to a certain point without rolling back the entire transaction. 

Syntax for Savepoint command: 

SAVEPOINT SAVEPOINT_NAME;

This command is used only in the creation of SAVEPOINT among all the transactions. 
In general ROLLBACK is used to undo a group of transactions. 

Syntax for roll back to Savepoint Command: 

ROLLBACK TO SAVEPOINT SAVEPOINT_NAME;

you can ROLLBACK to any SAVEPOINT at any time to return the appropriate data to its original state.

Example: 

From the above example Sample table1, Delete those records from the table which have age = 20 and then ROLLBACK the changes in the database by keeping Savepoints. 

Query

SAVEPOINT SP1;
//Savepoint created.
DELETE FROM Student WHERE AGE = 20;
//deleted
SAVEPOINT SP2;
//Savepoint created.

Here SP1 is first SAVEPOINT created before deletion.In this example one deletion have taken place. 
After deletion again SAVEPOINT SP2 is created. 

Output

output

output

Deletion have been taken place, let us assume that you have changed your mind and decided to ROLLBACK to the SAVEPOINT that you identified as SP1 which is before deletion. 
deletion is undone by this statement.

Query

ROLLBACK TO SP1;
//Rollback completed

Output

output

output

RELEASE SAVEPOINT Command

This command is used to remove a SAVEPOINT that you have created.

Syntax: 

RELEASE SAVEPOINT SAVEPOINT_NAME

Once a SAVEPOINT has been released, you can no longer use the ROLLBACK command to undo transactions performed since the last SAVEPOINT.
It is used to initiate a database transaction and used to specify characteristics of the transaction that follows. 

Conclusion

  • SQL statements are grouped together using transactions.
  • They promise that either all changes are made or none at all.
  • Reliability is ensured by the ACID qualities of atomicity, consistency, isolation, and durability.
  • Start a transaction with “BEGIN TRANSACTION,” and finish it with “COMMIT” or “ROLLBACK” to complete or undo changes.


Previous Article
Next Article

Similar Reads

Auto-commit commands and Compensating transactions in SQL
As the name suggests, the auto-commit statement is used to avoid the explicit mention of the commit command after each SQL statement. The commit statement itself gets executed by the server after each SQL statement. Each SQL statement is treated as a different transaction. An SQL statement executed in autocommit mode cannot be rolled back. Auto-com
3 min read
PL/SQL Transactions
PL/SQL transactions are vital components in database management, providing a means to maintain data integrity, consistency, and reliability within a relational database. A transaction in PL/SQL is defined as a series of SQL operations treated as a single unit of work. In this article, We will learn about PL/SQL Transactions in detail and so on. PL/
5 min read
Difference between Structured Query Language (SQL) and Transact-SQL (T-SQL)
Structured Query Language (SQL): Structured Query Language (SQL) has a specific design motive for defining, accessing and changement of data. It is considered as non-procedural, In that case the important elements and its results are first specified without taking care of the how they are computed. It is implemented over the database which is drive
2 min read
Configure SQL Jobs in SQL Server using T-SQL
In this article, we will learn how to configure SQL jobs in SQL Server using T-SQL. Also, we will discuss the parameters of SQL jobs in SQL Server using T-SQL in detail. Let's discuss it one by one. Introduction :SQL Server Agent is a component used for database task automation. For Example, If we need to perform index maintenance on Production ser
7 min read
SQL SERVER – Input and Output Parameter For Dynamic SQL
An Input Parameter can influence the subset of rows it returns from a select statement within it. A calling script can get the value of an output parameter. An aggregate function or any computational expression within the stored process can be used to determine the value of the output parameter. A parameter whose value is given into a stored proced
3 min read
Difference between T-SQL and PL-SQL
1. Transact SQL (T-SQL) : T-SQL is an abbreviation for Transact Structure Query Language. It is a product by Microsoft and is an extension of SQL Language which is used to interact with relational databases. It is considered to perform best with Microsoft SQL servers. T-SQL statements are used to perform the transactions to the databases. T-SQL has
3 min read
SQL Server | Convert tables in T-SQL into XML
In this, we will focus on how tables will be converted in T-SQL into XML in SQL server. And you will be able to understand how you can convert it with the help of command. Let's discuss it one by one. Overview :XML (Extensible Markup Language) is a markup language similar to HTML which was designed to share information between different platforms.
2 min read
SQL - SELECT from Multiple Tables with MS SQL Server
In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables. If we consider table1 contains m rows and table2 contains n
3 min read
How to Execute SQL Server Stored Procedure in SQL Developer?
A stored procedure is a set of (T-SQL ) statements needed in times when we are having the repetitive usage of the same query. When there is a need to use a large query multiple times we can create a stored procedure once and execute the same wherever needed instead of writing the whole query again. In this article let us see how to execute SQL Serv
2 min read
SQL Query to Check if Date is Greater Than Today in SQL
In this article, we will see the SQL query to check if DATE is greater than today's date by comparing date with today's date using the GETDATE() function. This function in SQL Server is used to return the present date and time of the database system in a ‘YYYY-MM-DD hh:mm: ss. mmm’ pattern. Features: This function is used to find the present date a
2 min read
SQL Query to Add a New Column After an Existing Column in SQL
Structured Query Language or SQL is a standard Database language that is used to create, maintain and retrieve data from relational databases like MySQL, Oracle, SQL Server, Postgres, etc. In Microsoft SQL Server, we can change the order of the columns and can add a new column by using ALTER command. ALTER TABLE is used to add, delete/drop or modif
3 min read
SQL Query to Convert Rows to Columns in SQL Server
In this article we will see, how to convert Rows to Column in SQL Server. In a table where many columns have the have same data for many entries in the table, it is advisable to convert the rows to column. This will help to reduce the table and make the table more readable. For example, Suppose we have a table given below: NAMECOLLEGEROLL NUMBERSUB
2 min read
How to SQL Select from Stored Procedure using SQL Server?
There may be situations in SQL Server where you need to use a stored procedure to get data from a SQL query. For direct data selection from a stored procedure within a query, SQL Server offers options like OPENQUERY and OPENROWSET. The usual way is running the stored procedure independently and then querying the outcomes. The idea of utilizing SQL
3 min read
SQL Quiz : Practice SQL Questions Online
This SQL quiz covers various topics like SQL basics, CRUD operations, operators, aggregation functions, constraints, joins, indexes, transactions, and query-based scenarios. We've included multiple-choice questions, fill-in-the-blank questions, and interactive coding challenges to keep things interesting and challenging. Whether you're a beginner l
3 min read
BULK INSERT in SQL Server(T-SQL command)
BULK INSERT in SQL Server(T-SQL command): In this article, we will cover bulk insert data from csv file using the T-SQL command in the SQL server and the way it is more useful and more convenient to perform such kind of operations. Let's discuss it one by one.  ConditionSometimes there is a scenario when we have to perform bulk insert data from .cs
3 min read
SQL Exercises : SQL Practice with Solution for Beginners and Experienced
SQL (Structured Query Language) is a powerful tool used for managing and manipulating relational databases. Whether we are beginners or experienced professionals, practicing SQL exercises is important for improving your skills. Regular practice helps you get better at using SQL and boosts your confidence in handling different database tasks. So, in
15+ min read
Difference between SQL and T-SQL
SQL (Structured Query Language) is the standard language for managing and manipulating relational databases, enabling operations like querying, updating, and deleting data. T-SQL (Transact-SQL), an extension of SQL developed by Microsoft, adds advanced features and procedural capabilities specifically for SQL Server. In this article, We will learn
4 min read
SQL Query to Find Number of Employees According to Gender Whose DOB is Between a Given Range
Query in SQL is like a statement that performs a task. Here, we need to write a query that will find the number of employees according to gender whose DOB is in the given range. We will first create a database named “geeks” then we will create a table “department” in that database. Creating a Database : Use the below SQL statement to create a datab
2 min read
Working With JSON in SQL
JSON stands for Javascript Object Notation. It is mainly used in storing and transporting data. Mostly all NoSQL databases like MongoDB, CouchDB, etc., use JSON format data. Whenever your data from one server has to be transferred to a web page, JSON format is the preferred format as front-end applications like Android, iOS, React or Angular, etc.,
7 min read
Dirty Read in SQL
Pre-Requisite - Types of Schedules, Transaction Isolation Levels in DBMS A Dirty Read in SQL occurs when a transaction reads data that has been modified by another transaction, but not yet committed. In other words, a transaction reads uncommitted data from another transaction, which can lead to incorrect or inconsistent results. This situation can
6 min read
QUOTENAME() Function in SQL Server
QUOTENAME() function : This function in SQL Server is used to return a Unicode string with delimiters added in order to make the string a valid SQL Server delimited identifier. Features : This function is used to find a Unicode string with delimiters added. This function accepts only strings and delimiters. This function add delimiters by default i
3 min read
Print all even numbers from 1 to n in PL/SQL
Prerequisite- PL/SQL Introduction In PL/SQL code groups of commands are arranged within a block. It groups together related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Given a number N, the task is to display all the even numbers and their sum from 1 to N. Examples: In
1 min read
Removing Duplicate Rows (Based on Values from Multiple Columns) From SQL Table
In SQL, some rows contain duplicate entries in multiple columns(>1). For deleting such rows, we need to use the DELETE keyword along with self-joining the table with itself. The same is illustrated below. For this article, we will be using the Microsoft SQL Server as our database. Step 1: Create a Database. For this use the below command to crea
3 min read
SQL | Arithmetic Operators
Prerequisite: Basic Select statement, Insert into clause, Sql Create Clause, SQL Aliases We can use various Arithmetic Operators on the data stored in the tables. Arithmetic Operators are: + [Addition] - [Subtraction] / [Division] * [Multiplication] % [Modulus] Addition (+) : It is used to perform addition operation on the data items, items include
5 min read
SQL | Top-N Queries
Top-N Analysis in SQL deals with How to limit the number of rows returned from ordered sets of data in SQL. Top-N queries ask for the n smallest or largest values of a column. Both smallest and largest values sets are considered Top-N queries. Following this type of searching technique could save lot of time and complexities. Top-N analysis are use
4 min read
Reverse a number in PL/SQL
Prerequisite - PL/SQL introduction In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations. Explanation: Consider the example, input = 12345. Step 1 : mod(12345,10) = 5 rev:= 0*10 + 5 = 5 num = flo
2 min read
Print different star patterns in SQL
Let's see how we can print the pattern of various type using SQL. Syntax : Declare @variable_name DATATYPE -- first declare all the -- variables with datatype -- like (int) select @variable = WITH_ANY_VALUE -- select the variable and -- initialize with value while CONDITION -- condition like @variable > 0 begin -- begin print replicate('*', @var
2 min read
SQL Indexes
An index is a schema object. It is used by the server to speed up the retrieval of rows by using a pointer. It can reduce disk I/O(input/output) by using a rapid path access method to locate data quickly. An index helps to speed up select queries and where clauses, but it slows down data input, with the update and the insert statements. Indexes can
5 min read
SQL | Intersect & Except clause
1. INTERSECT clause : As the name suggests, the intersect clause is used to provide the result of the intersection of two select statements. This implies the result contains all the rows which are common to both the SELECT statements. Syntax : SELECT column-1, column-2 …… FROM table 1 WHERE….. INTERSECT SELECT column-1, column-2 …… FROM table 2 WHE
1 min read
SQL | USING Clause
If several columns have the same names but the datatypes do not match, the NATURAL JOIN clause can be modified with the USING clause to specify the columns that should be used for an EQUIJOIN. USING Clause is used to match only one column when more than one column matches. NATURAL JOIN and USING Clause are mutually exclusive. It should not have a q
2 min read
Article Tags :