SQL Transactions
Chapter 36 of 40 · Estimated read time: 10 min
A transaction is a group of SQL statements that must all succeed or all fail together. If any statement in the group fails, every change made by the group is reversed — leaving the database exactly as it was before. Transactions are the safety net that keeps data correct when things go wrong.
Imagine processing an order: you need to deduct stock from the products table AND insert a row into the orders table. If the first statement succeeds but the database crashes before the second runs, you have reduced stock with no matching order — corrupted data.
-- WITHOUT a transaction — dangerous!
UPDATE products SET stock = stock - 1 WHERE product_id = 'P01';
-- ← server crashes here
INSERT INTO orders (customer_id, product_id, total_amount)
VALUES ('C06', 'P01', 899);
-- Stock deducted, order never recorded ❌ACID — The Four Properties of a Transaction
Transaction Syntax
Example 1 — A Successful Transaction (COMMIT)
Process a new order safely — insert the order and update the stock in a single atomic unit:
START TRANSACTION; -- Step 1: insert the order INSERT INTO orders (order_id, customer_id, product_id, order_date, total_amount) VALUES (1008, 'C02', 'P01', CURDATE(), 899); -- Step 2: reduce stock UPDATE products SET stock = stock - 1 WHERE product_id = 'P01'; -- Both succeeded — make it permanent COMMIT;
| What changed | Before | After |
|---|---|---|
| orders table rows | 7 | 8 (order 1008 added) |
| Wireless Mouse stock | 10 | 9 (reduced by 1) |
Example 2 — Catching an Error and Rolling Back
If anything looks wrong during the transaction, ROLLBACK reverses every change made since START TRANSACTION:
START TRANSACTION; INSERT INTO orders (order_id, customer_id, product_id, order_date, total_amount) VALUES (1009, 'C99', 'P01', CURDATE(), 899); -- C99 does not exist! Foreign key violation detected. -- Do NOT commit — undo everything ROLLBACK; -- Database is exactly as it was before START TRANSACTION -- orders table still has 7 rows, stock unchanged
| What changed | Before | After ROLLBACK |
|---|---|---|
| orders table rows | 7 | 7 (insert reversed) |
| Wireless Mouse stock | 10 | 10 (unchanged) |
SAVEPOINT — Partial Rollback
A SAVEPOINT marks a point inside a transaction you can roll back to without undoing the entire transaction:
START TRANSACTION; -- Batch 1: update Noida customers' discount UPDATE customers SET discount_pct = 12 WHERE city = 'Noida'; SAVEPOINT after_noida_update; -- Batch 2: update Delhi customers' discount UPDATE customers SET discount_pct = 8 WHERE city = 'Delhi'; -- Oops — wrong discount for Delhi, but Noida update was fine -- Roll back only the Delhi update, keep the Noida update ROLLBACK TO SAVEPOINT after_noida_update; -- Now commit just the Noida change COMMIT;
Autocommit — The Default Behaviour
By default, most databases run in autocommit mode — every individual statement is automatically committed the moment it succeeds. This is why a bare DELETE FROM orders WHERE order_id = 1001 is permanent with no COMMIT needed.
-- Check autocommit mode (MySQL) SHOW VARIABLES LIKE 'autocommit'; -- ON by default -- Turn it off for this session (manual commit required) SET autocommit = 0; -- Now statements are NOT committed until you COMMIT explicitly DELETE FROM orders WHERE order_id = 1001; -- Row appears deleted to your session but not saved yet ROLLBACK; -- row comes back! -- Turn autocommit back on SET autocommit = 1;
DDL Statements and Transactions
| Statement type | Examples | Can be rolled back? |
|---|---|---|
| DML | INSERT, UPDATE, DELETE | ✅ Yes — wrap in a transaction |
| DDL (MySQL) | CREATE TABLE, ALTER TABLE, DROP TABLE | ❌ No — causes implicit COMMIT first |
| DDL (PostgreSQL) | CREATE TABLE, ALTER TABLE, DROP TABLE | ✅ Yes — PostgreSQL supports transactional DDL |
| DCL | GRANT, REVOKE | ❌ No — takes effect immediately |
Show Answers
-- 1.
START TRANSACTION;
INSERT INTO customers (customer_id, customer_name, city)
VALUES ('C06', 'Kavita Rao', 'Pune');
INSERT INTO orders (order_id, customer_id, product_id, order_date, total_amount)
VALUES (1010, 'C06', 'P03', CURDATE(), 99);
COMMIT;
-- 2.
START TRANSACTION;
DELETE FROM orders WHERE total_amount < 300;
-- In a real scenario you'd check ROW_COUNT() after the DELETE
-- If ROW_COUNT() > 2 then ROLLBACK; else COMMIT;
-- MySQL example using a variable:
SET @removed = ROW_COUNT();
IF @removed > 2 THEN
ROLLBACK;
ELSE
COMMIT;
END IF;
-- 3.
-- ROLLBACK: undoes the ENTIRE transaction from the beginning.
-- Use when the whole operation must be retried or abandoned.
-- Example: a payment fails — reverse the stock deduction,
-- the order insert, and the invoice creation all at once.
-- ROLLBACK TO SAVEPOINT: undoes only back to the named point.
-- The earlier work in the transaction is preserved.
-- Example: a 3-city discount update — cities 1 and 2 succeed,
-- city 3 fails validation. Roll back to the savepoint after
-- city 2 and commit the first two updates without redoing them.