Transactions in SQL
Understanding SQL Transactions with ACID
properties and control commands
What is a • A transaction in SQL is a sequence of one or more
SQL operations executed as a single logical unit of
Transaction? work. It ensures data consistency and integrity.
ACID Properties of Transactions
ATOMICITY – ALL CONSISTENCY – THE ISOLATION – TRANSACTIONS DURABILITY – COMMITTED
OPERATIONS IN A DATABASE REMAINS IN A RUN INDEPENDENTLY DATA IS PERMANENT
TRANSACTION ARE VALID STATE BEFORE AND WITHOUT INTERFERENCE.
COMPLETED, OR NONE ARE. AFTER THE TRANSACTION.
Transaction • START TRANSACTION / BEGIN – Starts a
transaction
Control • COMMIT – Saves all changes
• ROLLBACK – Undoes changes
Commands • SAVEPOINT – Creates intermediate point
• RELEASE SAVEPOINT – Deletes a savepoint
MySQL Savepoints and
Transaction Control
Demonstration of Savepoints, Rollback, DDL
Effects, and Commit Behavior
Table Setup
• CREATE TABLE employee (
id INT PRIMARY KEY,
name VARCHAR(50),
salary INT
);
• START TRANSACTION;
• INSERT INTO employee VALUES (1,
'Alice', 50000);
• SAVEPOINT S1;
• INSERT INTO employee VALUES (2,
'Bob', 55000);
• SAVEPOINT S2;
Create • INSERT INTO employee VALUES (3,
'Charlie', 60000);
Savepoints • SAVEPOINT S3;
• INSERT INTO employee VALUES (4,
'David', 62000);
• SAVEPOINT S4;
• INSERT INTO employee VALUES (5,
'Eva', 58000);
• SAVEPOINT S5;
• ROLLBACK TO SAVEPOINT S3;
• -- Output:
1 | Alice | 50000
Rollback to 2 | Bob | 55000
3 | Charlie | 60000
Savepoints
• ROLLBACK TO SAVEPOINT S1;
• -- Output:
1 | Alice | 50000
• START TRANSACTION;
• INSERT INTO employee VALUES (6,
'Frank', 57000);
Abnormal • -- Exit MySQL client without
Termination •
COMMIT
-- Restart and check:
Behavior
• SELECT * FROM employee WHERE
id = 6;
• -- Output: No result (data not
saved)
• START TRANSACTION;
• INSERT INTO employee VALUES (7,
'Grace', 61000);
Using COMMIT • COMMIT;
and COMMIT • START TRANSACTION;
WORK • INSERT INTO employee VALUES (8,
'Hassan', 53000);
• COMMIT WORK;
• -- Data is permanently saved.