EVIKA.ACADEMY›SQL Tutorial
SQL Tutorial›Transactions

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.

Why Transactions Exist — The Classic Problem

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 ❌
A transaction wraps both statements so either BOTH succeed or NEITHER happens.

ACID — The Four Properties of a Transaction

AAtomicity
All statements in the transaction succeed, or none do. No partial results.
CConsistency
The database moves from one valid state to another. No rules are broken.
IIsolation
Concurrent transactions do not interfere with each other mid-flight.
DDurability
Once committed, the data is permanent — even if the server restarts.

Transaction Syntax

START TRANSACTION; -- or BEGIN; (MySQL also accepts BEGIN TRANSACTION) statement_1; statement_2; statement_3; COMMIT; -- make all changes permanent -- If something goes wrong: ROLLBACK; -- undo everything since START TRANSACTION

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;
State after COMMIT — both changes are permanent
What changedBeforeAfter
orders table rows78 (order 1008 added)
Wireless Mouse stock109 (reduced by 1)
Between START TRANSACTION and COMMIT, only your session can see the uncommitted changes. Other sessions still see the old data until you COMMIT — this is the Isolation property of ACID.

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
State after ROLLBACK — nothing changed
What changedBeforeAfter ROLLBACK
orders table rows77 (insert reversed)
Wireless Mouse stock1010 (unchanged)

SAVEPOINT — Partial Rollback

A SAVEPOINT marks a point inside a transaction you can roll back to without undoing the entire transaction:

SAVEPOINT savepoint_name; ROLLBACK TO SAVEPOINT savepoint_name; -- undo back to this point only RELEASE SAVEPOINT savepoint_name; -- remove the savepoint
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;
SAVEPOINTs are useful in long batch operations where early steps are correct and only later steps fail. Without a SAVEPOINT you would have to re-run all the earlier steps after a full ROLLBACK.

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;
Always use START TRANSACTION explicitly rather than toggling autocommit — it is clearer, less error-prone, and works the same way across all databases. Leaving autocommit off globally is a common source of "where did my data go?" bugs.

DDL Statements and Transactions

Statement typeExamplesCan be rolled back?
DMLINSERT, 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
DCLGRANT, REVOKE❌ No — takes effect immediately
In MySQL, running a DDL statement (CREATE TABLE, DROP TABLE, ALTER TABLE) inside a transaction automatically commits any pending DML first. This is a common gotcha — always finish your DML transactions before running DDL.
✏️ Practice Exercises
1. Write a transaction that inserts a new customer (C06, Kavita Rao, Pune) and immediately places an order for them (order_id 1010, product P03, ₹99). COMMIT if both succeed.
2. Write a transaction that deletes all orders where total_amount < 300, then immediately checks the count — if the count removed is more than 2, ROLLBACK; otherwise COMMIT.
3. What is the difference between ROLLBACK and ROLLBACK TO SAVEPOINT? Give a scenario where each is the right choice.
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.