Transactions are fundamental in SQL for ensuring data integrity, especially in environments where multiple users access and manipulate the database concurrently. This section covers transaction management commands, the ACID properties that guarantee reliable transactions, isolation levels that control visibility between transactions, and concepts of locks and deadlocks.
1. Transaction Management
A transaction is typically a sequence of one or more SQL statements that are executed as a single unit of work. The primary commands for managing transactions are:
Transaction Commands
Command | Description | SQL Server Syntax | MySQL Syntax | PostgreSQL Syntax |
BEGIN TRANSACTION | Starts a new transaction. | BEGIN TRANSACTION; | START TRANSACTION; | BEGIN; |
COMMIT | Saves all changes made during the transaction. | COMMIT; | COMMIT; | COMMIT; |
ROLLBACK | Undoes changes made during the transaction. | ROLLBACK; | ROLLBACK; | ROLLBACK; |
Example: Basic Transaction
-- SQL Server
BEGIN TRANSACTION;
INSERT INTO Employees (FirstName, LastName, HireDate) VALUES ('Alice', 'Smith', GETDATE());
COMMIT;
-- MySQL
START TRANSACTION;
INSERT INTO Employees (FirstName, LastName, HireDate) VALUES ('Bob', 'Brown', NOW());
COMMIT;
-- PostgreSQL
BEGIN;
INSERT INTO Employees (FirstName, LastName, HireDate) VALUES ('Charlie', 'Davis', CURRENT_TIMESTAMP);
COMMIT;
2. ACID Properties
The ACID properties are crucial for ensuring that database transactions are processed reliably:
- Atomicity: Ensures that all operations in a transaction are completed; if one fails, the entire transaction fails.
- Consistency: Guarantees that a transaction brings the database from one valid state to another, maintaining all predefined rules (constraints).
- Isolation: Ensures that transactions occur independently without interference. Changes made in one transaction are not visible to others until committed.
- Durability: Guarantees that once a transaction is committed, its effects are permanently recorded in the database, even in case of a system failure.
Example:
BEGIN TRANSACTION;
-- Assuming an account transfer
UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 1; -- Withdraw
UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 2; -- Deposit
-- Check if both updates are successful
IF @@ERROR <> 0
BEGIN
ROLLBACK; -- If there was an error, undo all changes
END
ELSE
BEGIN
COMMIT; -- If successful, save changes
END
3. Isolation Levels
Isolation levels define how transactions interact with each other and how data integrity is maintained. The common isolation levels include:
Isolation Level | Description | SQL Server Syntax | MySQL Syntax | PostgreSQL Syntax |
READ UNCOMMITTED | Allows reading uncommitted changes from other transactions. | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; | SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; |
READ COMMITTED | Default level; only committed changes are readable. | SET TRANSACTION ISOLATION LEVEL READ COMMITTED; | SET TRANSACTION ISOLATION LEVEL READ COMMITTED; | SET TRANSACTION ISOLATION LEVEL READ COMMITTED; |
REPEATABLE READ | Ensures that if a row is read twice, it remains unchanged. | SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; | SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; | SET TRANSACTION ISOLATION LEVEL REPEATABLE READ; |
SERIALIZABLE | Highest level; transactions are completely isolated. | SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; | SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; | SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; |
Example:
-- Set isolation level in SQL Server
-- Similar commands can be used for MySQL and PostgreSQL
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
SELECT * FROM Accounts WHERE AccountID = 1;
COMMIT;
4. Locks and Deadlocks
Locks are mechanisms to control access to data during a transaction. They ensure that multiple transactions do not interfere with each other, preserving data integrity.
Types of Locks:
- Shared Locks: Allow concurrent transactions to read a resource but not modify it.
- Exclusive Locks: Prevent other transactions from reading or modifying a resource.
Deadlocks:
A deadlock occurs when two or more transactions are simultaneously waiting for each other to release locks, causing them to remain indefinitely blocked.
Detecting and Resolving Deadlocks:
Most database systems have built-in deadlock detection mechanisms that automatically terminate one of the transactions to resolve the deadlock.
Example:
-- SQL Server Example of Locking
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 50 WHERE AccountID = 1; -- Locks row for AccountID 1
WAITFOR DELAY '00:00:10'; -- Simulating a delay
UPDATE Accounts SET Balance = Balance + 50 WHERE AccountID = 2; -- This could cause a deadlock if another transaction is locking AccountID 2
COMMIT;
Conclusion
Understanding transactions and concurrency control is crucial for maintaining data integrity in relational databases. By using transactions effectively, ensuring adherence to ACID properties, and managing isolation levels, you can mitigate issues related to data inconsistency and concurrency. Additionally, awareness of locks and deadlocks allows for more robust transaction management.
Most Commented