SQL Transactions & Concurrency: Master ACID, COMMIT/ROLLBACK, Isolation Levels, Locking, Deadlocks with Examples & Best Practices

Table of Contents

1. What is a transaction in SQL?

SQL Transactions Overview: Unit of Work with COMMIT/ROLLBACK

A transaction is a sequence of SQL operations (e.g., INSERT, UPDATE, DELETE) treated as a single unit of work that must succeed or fail entirely. Transactions ensure data consistency and integrity in a database.

Syntax:

BEGIN TRANSACTION;
-- SQL statements
COMMIT;
-- or ROLLBACK;

Supported across RDBMS (MySQL, PostgreSQL, SQL Server, SQLite), with variations (e.g., START TRANSACTION in MySQL).

2. What are the ACID properties of a transaction?

ACID Properties in DBMS: Atomicity, Consistency, Isolation, Durability Diagram

ACID Properties Detailed Explanation with Examples

ACID ensures reliable transactions:

3. Can you give an example of a transaction with ACID properties?

SQL Transaction COMMIT/ROLLBACK Flowchart for Bank Transfer Example

-- Create sample tables
CREATE TABLE Accounts (
  AccountID INT PRIMARY KEY,
  AccountHolder VARCHAR(50),
  Balance DECIMAL(10, 2)
);
-- Insert sample data
INSERT INTO Accounts (AccountID, AccountHolder, Balance)
VALUES (1, 'John', 1000.00), (2, 'Jane', 500.00);

-- Transaction: Transfer $200 from John to Jane
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 200.00 WHERE AccountID = 1;
UPDATE Accounts SET Balance = Balance + 200.00 WHERE AccountID = 2;
-- Check if John has enough balance
IF (SELECT Balance FROM Accounts WHERE AccountID = 1) >= 0
  COMMIT;
ELSE
  ROLLBACK;

-- Verify data
SELECT * FROM Accounts;

Output:

AccountID | AccountHolder | Balance
----------|--------------|--------
1         | John         | 800.00
2         | Jane         | 700.00

Note:

4. What are COMMIT and ROLLBACK?

COMMIT: Permanently saves all changes made in the transaction to the database.

ROLLBACK: Undoes all changes made in the transaction, restoring the database to its state before the transaction began.

Syntax:

BEGIN TRANSACTION;
-- SQL statements
COMMIT; -- Save changes
-- or
ROLLBACK; -- Undo changes

Use Case: Use COMMIT for successful operations; use ROLLBACK for errors or invalid states (e.g., insufficient balance in a transfer).

5. Can you give an example of COMMIT and ROLLBACK?

-- Transaction with error handling
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 1000.00 WHERE AccountID = 1;
-- Simulate an error: insufficient balance
IF (SELECT Balance FROM Accounts WHERE AccountID = 1) < 0
BEGIN
  ROLLBACK;
  SELECT 'Transaction rolled back: Insufficient balance' AS Message;
END
ELSE
BEGIN
  UPDATE Accounts SET Balance = Balance + 1000.00 WHERE AccountID = 2;
  COMMIT;
  SELECT 'Transaction committed' AS Message;
END;

-- Verify data
SELECT * FROM Accounts;

Output:

Message
--------------------------------
Transaction rolled back: Insufficient balance

AccountID | AccountHolder | Balance
----------|--------------|--------
1         | John         | 800.00
2         | Jane         | 700.00

Note: The transaction rolls back because John's balance (800.00) is insufficient for a 1000.00 transfer, preserving the original state.

6. What are isolation levels in SQL?

SQL Isolation Levels Comparison Chart: Dirty Read, Non-Repeatable Read, Phantom Read

Transaction Isolation Levels Detailed Table with Concurrency Issues

Isolation levels define how transactions are isolated from each other, balancing data consistency with performance. They control the visibility of uncommitted changes and prevent concurrency issues (e.g., dirty reads, non-repeatable reads, phantoms).

Standard Isolation Levels (SQL Standard):

Syntax (varies by RDBMS):

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
-- SQL statements
COMMIT;

Support: MySQL, PostgreSQL, SQL Server support all levels; SQLite supports SERIALIZABLE and READ UNCOMMITTED.

7. Can you give an example of isolation levels?

-- Set isolation level to Read Committed
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
BEGIN TRANSACTION;
SELECT Balance FROM Accounts WHERE AccountID = 1;
-- Assume another session updates Balance but doesn't commit
-- This transaction sees only committed data
COMMIT;

-- Verify data
SELECT * FROM Accounts;

Output:

AccountID | AccountHolder | Balance
----------|--------------|--------
1         | John         | 800.00
2         | Jane         | 700.00

Note: In READ COMMITTED, the transaction sees only committed changes, preventing dirty reads from concurrent updates.

8. What is locking in databases?

Shared Locks in DBMS: Multiple Readers Allowed Diagram

Exclusive Locks in DBMS: Single Writer Blocking Others Diagram

Locking is a mechanism to control concurrent access to data, preventing conflicts when multiple transactions access the same resources.

Types of Locks:

Syntax (varies by RDBMS):

-- Explicit locking (SQL Server)
SELECT * FROM Accounts WITH (ROWLOCK, UPDLOCK);
-- Implicit locking occurs during DML operations

9. Can you give an example of locking?

-- Transaction with explicit locking (SQL Server syntax)
BEGIN TRANSACTION;
SELECT Balance FROM Accounts WITH (UPDLOCK) WHERE AccountID = 1;
-- Update balance (exclusive lock acquired)
UPDATE Accounts SET Balance = Balance - 100.00 WHERE AccountID = 1;
COMMIT;

-- Verify data
SELECT * FROM Accounts;

Output:

AccountID | AccountHolder | Balance
----------|--------------|--------
1         | John         | 700.00
2         | Jane         | 700.00

Note: UPDLOCK ensures no other transaction modifies the row until the transaction commits, preventing conflicts.

10. What is a deadlock in databases?

A deadlock occurs when two or more transactions wait indefinitely for each other to release locks, creating a cycle.

Example: Transaction A locks Row 1 and waits for Row 2; Transaction B locks Row 2 and waits for Row 1.

Resolution: RDBMS detects deadlocks and terminates one transaction, rolling it back.

Prevention: Minimize lock duration, access resources in a consistent order, use appropriate isolation levels.

11. Can you give an example of a deadlock scenario?

Database Deadlock Cycle Example with Two Transactions

Deadlock in DBMS Visual Explanation with Wait-For Graph

-- Session 1
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 100.00 WHERE AccountID = 1;
-- Waits for AccountID 2
UPDATE Accounts SET Balance = Balance + 100.00 WHERE AccountID = 2;
COMMIT;

-- Session 2 (run concurrently)
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 50.00 WHERE AccountID = 2;
-- Waits for AccountID 1
UPDATE Accounts SET Balance = Balance + 50.00 WHERE AccountID = 1;
COMMIT;

Note:

12. Can you provide a comprehensive example using transactions, ACID, isolation levels, locking, and deadlock handling?

-- Create sample table
CREATE TABLE Accounts (
  AccountID INT PRIMARY KEY,
  AccountHolder VARCHAR(50),
  Balance DECIMAL(10, 2)
);
-- Insert sample data
INSERT INTO Accounts (AccountID, AccountHolder, Balance)
VALUES (1, 'John', 1000.00), (2, 'Jane', 500.00);

-- Transaction with isolation level and locking
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
BEGIN TRANSACTION;
-- Lock row for update
SELECT Balance FROM Accounts WITH (UPDLOCK) WHERE AccountID = 1;
-- Transfer $200 from John to Jane
UPDATE Accounts SET Balance = Balance - 200.00 WHERE AccountID = 1;
-- Check balance to ensure validity
IF (SELECT Balance FROM Accounts WHERE AccountID = 1) < 0
BEGIN
  ROLLBACK;
  SELECT 'Transaction rolled back: Insufficient balance' AS Message;
END
ELSE
BEGIN
  UPDATE Accounts SET Balance = Balance + 200.00 WHERE AccountID = 2;
  COMMIT;
  SELECT 'Transaction committed' AS Message;
END;

-- Verify data
SELECT * FROM Accounts;

Output:

Message
--------------------
Transaction committed

AccountID | AccountHolder | Balance
----------|--------------|--------
1         | John         | 800.00
2         | Jane         | 700.00

Description:

13. What are common mistakes in transactions and concurrency?

Transactions:

Isolation Levels:

Locking:

Deadlocks:

14. What are best practices for transactions and concurrency?

Database Transactions and Concurrency Best Practices Infographic

Transactions:

Isolation Levels:

Locking:

Deadlocks:

General: