An SQL transaction is a sequence of one or more SQL operations (e.g., INSERT
, UPDATE
, DELETE
) executed as a single unit of work. Transactions ensure that either all operations succeed or none are applied, maintaining data integrity.
Key Properties of SQL Transactions: ACID
The integrity of SQL transactions is governed by the ACID properties, which guarantee reliable database transactions. These four properties work together to guarantee that the database remains consistent and reliable.
- 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.
SQL Transaction Control Commands
In SQL, transaction control commands manage the execution of SQL operations, ensuring the integrity and reliability of database transactions. These commands help manage the start, commit, and rollback of changes made to the database. Below are the key transaction control commands in SQL, explained with syntax and examples for each.
1. BEGIN TRANSACTION Command
The BEGIN TRANSACTION
command marks the beginning of a new transaction. All SQL statements that follow this command will be part of the same transaction until a COMMIT
or ROLLBACK
is encountered. This command doesn't make any changes to the database, it just starts the transaction.
Syntax:
BEGIN TRANSACTION transaction_name ;
Example of SQL Transaction with a Bank Transfer Scenario
Let’s look at an example of a bank transfer between two accounts. This example demonstrates the usage of multiple queries in a single transaction.
BEGIN TRANSACTION;
-- Deduct $150 from Account A
UPDATE Accounts
SET Balance = Balance - 150
WHERE AccountID = 'A';
-- Add $150 to Account B
UPDATE Accounts
SET Balance = Balance + 150
WHERE AccountID = 'B';
-- Commit the transaction if both operations succeed
COMMIT;
If any error occurs, such as an issue with the UPDATE
query, you can use ROLLBACK
to undo all changes made during the transaction:
ROLLBACK;
This ensures that the system doesn't end up in an inconsistent state, such as deducting money from one account without adding it to another.
BEGIN TRANSACTION TransferFunds;
2. COMMIT Command
The COMMIT
command is used to save all changes made during the current transaction to the database. Once a transaction is committed, the changes are permanent.
Syntax:
COMMIT;
Example
Here is the sample Student
table that will be used to perform the operations in this example. This table contains basic student details such as ID, name, age, and other relevant information that will be manipulated using various transaction control commands.
Student TableFollowing is an example which would delete those records from the table which have age = 20 and then COMMIT the changes in the database.
DELETE FROM Student WHERE AGE = 20;
COMMIT;
Output
output3. ROLLBACK Command
The ROLLBACK
command is used to undo all changes made in the current transaction. It is used when an error occurs or when the desired changes cannot be completed. The database will revert to the state it was in before the BEGIN TRANSACTION
was executed.
Syntax:
ROLLBACK;
Example
Delete those records from the table which have age = 20 and then ROLLBACK the changes in the database. In this case, the DELETE
operation is undone, and the changes to the database are not saved.
DELETE FROM Student WHERE AGE = 20;
ROLLBACK;
Output:
output4. SAVEPOINT Command
A SAVEPOINT
is used to create a checkpoint within a transaction. We can roll back to a specific SAVEPOINT
instead of rolling back the entire transaction. This allows us to undo part of the transaction rather than the entire transaction.
Syntax:
SAVEPOINT SAVEPOINT_NAME;
Example
SAVEPOINT SP1;
//Savepoint created.
DELETE FROM Student WHERE AGE = 20;
//deleted
SAVEPOINT SP2;
//Savepoint created.
Output:
outputExplanation:
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. Here SP1 is first SAVEPOINT created before deletion. In this example one deletion have taken place. After deletion again SAVEPOINT SP2 is created.
5. ROLLBACK TO SAVEPOINT
The ROLLBACK TO SAVEPOINT
command allows us to roll back the transaction to a specific savepoint, effectively undoing changes made after that point.
Syntax:
ROLLBACK TO SAVEPOINT SAVEPOINT_NAME;
Example
Deletion have been taken place, let us assume that we have changed our mind and decided to ROLLBACK to the SAVEPOINT that we identified as SP1 which is before deletion. So, In this case the DELETE
operation is undone, and the transaction is returned to the state it was in at the SP1
savepoint.
ROLLBACK TO SP1;
//Rollback completed
Output:
output6. RELEASE SAVEPOINT Command
This command is used to remove a SAVEPOINT that we have created. Once a SAVEPOINT has been released, we 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.
Syntax:
RELEASE SAVEPOINT SAVEPOINT_NAME;
Example
Once the savepoint SP2
is released, we can no longer roll back to it.
RELEASE SAVEPOINT SP2; -- Release the second savepoint.
Why Use Transactions in Banking?
In this case, without a transaction, you risk scenarios where money is deducted from one account but not added to the other, leaving the system in an inconsistent state. Transactions ensure that such issues are avoided by guaranteeing that both operations succeed or fail together.
Types of SQL Transactions
There are different types of transactions based on their nature and the specific operations they perform:
- Read Transactions: Used to only read the data, typically with
SELECT
queries.
- Write Transactions: These involve modifying the data in the database with
INSERT
, UPDATE
, or DELETE
operations.
- Distributed Transactions: These transactions span multiple databases and ensure consistency across them.
- Implicit Transactions: Automatically started by SQL Server for certain operations.
- Explicit Transactions: Manually controlled transactions where the user begins and ends the transaction using
BEGIN TRANSACTION
, COMMIT
, and ROLLBACK
.
Monitoring and Optimizing SQL Transactions
To maintain performance and prevent issues, consider the following techniques:
1. Monitor Locks: Track locking behavior and adjust queries to minimize locking conflicts.
2. Limit Transaction Scope: Limit the number of rows or records affected by a transaction to speed up processing.
3. Use Batch Processing: If you're handling large amounts of data, break the operations into smaller transactions or batches to avoid overwhelming the system.
Explore
SQL Tutorial
7 min read
Basics
Queries & Operations
SQL Joins & Functions
Data Constraints & Aggregate Functions
Advanced SQL Topics
Database Design & Security