MySQL Transactions
A transaction groups several statements into one unit of work that either happens completely or not at all. The textbook example is a money transfer: subtracting from one account and adding to another must never be half-done.
Transactions give four guarantees, known as ACID:
| Letter | Property | Meaning |
|---|---|---|
| A | Atomicity | all statements take effect, or none do |
| C | Consistency | constraints hold before and after |
| I | Isolation | concurrent transactions don't see each other's unfinished work |
| D | Durability | once committed, the change survives a crash |
In MySQL, transactions need a transactional storage engine. InnoDB, the default, is one.
Autocommit
By default MySQL runs in autocommit mode: every statement is its own transaction and is committed immediately. To group statements, start a transaction explicitly:
START TRANSACTION; -- or BEGIN
... statements ...
COMMIT; -- make the changes permanent
-- or
ROLLBACK; -- undo everything since START TRANSACTIONROLLBACK undoes the work
START TRANSACTION;
DELETE FROM order_details WHERE order_id = 22;
DELETE FROM orders WHERE order_id = 22;
SELECT COUNT(*) AS orders_inside_transaction FROM orders;
ROLLBACK;
SELECT COUNT(*) AS orders_after_rollback FROM orders;+---------------------------+
| orders_inside_transaction |
+---------------------------+
| 21 |
+---------------------------+
+-----------------------+
| orders_after_rollback |
+-----------------------+
| 22 |
+-----------------------+
Inside the transaction we see our own changes; after ROLLBACK the order and its lines are back.
COMMIT makes it permanent
Placing an order touches several tables. Wrapping the steps in a transaction means a failure halfway leaves no orphaned order and no stock reduced for nothing:
START TRANSACTION;
INSERT INTO orders (customer_id, employee_id, order_date, status)
VALUES (7, 5, '2025-06-06', 'processing');
SET @oid = LAST_INSERT_ID();
INSERT INTO order_details (order_id, product_id, quantity, unit_price)
VALUES (@oid, 17, 2, 5.49);
UPDATE products SET units_in_stock = units_in_stock - 2 WHERE product_id = 17;
COMMIT;
SELECT o.order_id, o.customer_id, d.product_id, d.quantity, p.units_in_stock
FROM orders AS o
JOIN order_details AS d ON d.order_id = o.order_id
JOIN products AS p ON p.product_id = d.product_id
WHERE o.order_id = @oid;+----------+-------------+------------+----------+----------------+
| order_id | customer_id | product_id | quantity | units_in_stock |
+----------+-------------+------------+----------+----------------+
| 23 | 7 | 17 | 2 | 63 |
+----------+-------------+------------+----------+----------------+
In application code the pattern is: start, run the statements, COMMIT if all succeeded, ROLLBACK in the error handler.
SAVEPOINT: partial rollback
A savepoint marks a point inside a transaction that you can roll back to without abandoning the whole transaction:
START TRANSACTION;
UPDATE products SET unit_price = 25.00 WHERE product_id = 1;
SAVEPOINT after_coffee;
UPDATE products SET unit_price = 0.01 WHERE product_id = 2; -- oops
ROLLBACK TO SAVEPOINT after_coffee;
COMMIT;
SELECT product_id, name, unit_price FROM products WHERE product_id IN (1, 2);+------------+--------------------+------------+
| product_id | name | unit_price |
+------------+--------------------+------------+
| 1 | Espresso Beans 1kg | 25.00 |
| 2 | Earl Grey Tea | 6.75 |
+------------+--------------------+------------+
The coffee price change was kept; the mistaken tea price was undone.
Statements that commit implicitly
DDL statements such as CREATE TABLE, ALTER TABLE, DROP TABLE and TRUNCATE commit the current transaction before they run, and can't be rolled back themselves:
START TRANSACTION;
UPDATE customers SET city = 'Porto' WHERE customer_id = 1;
CREATE TABLE audit_note (txt VARCHAR(20)); -- commits the UPDATE!
ROLLBACK;
SELECT first_name, city FROM customers WHERE customer_id = 1;+------------+-------+
| first_name | city |
+------------+-------+
| Ana | Porto |
+------------+-------+
The ROLLBACK had nothing left to undo. Keep schema changes out of data transactions.
Isolation levels and locking
While a transaction runs, other connections keep working. The isolation level decides what they can see of each other's changes:
| Level | Dirty reads | Non-repeatable reads | Phantom rows |
|---|---|---|---|
READ UNCOMMITTED |
possible | possible | possible |
READ COMMITTED |
no | possible | possible |
REPEATABLE READ (InnoDB default) |
no | no | mostly prevented |
SERIALIZABLE |
no | no | no |
SELECT @@autocommit AS autocommit, @@transaction_isolation AS isolation;+------------+-----------------+
| autocommit | isolation |
+------------+-----------------+
| 1 | REPEATABLE-READ |
+------------+-----------------+
Under REPEATABLE READ, a transaction reads from a consistent snapshot: repeating a SELECT gives the same answer even if others commit changes meanwhile. Writes lock the rows they change until commit, so two transactions updating the same row wait for each other. To read a row you intend to update and lock it at once, use SELECT ... FOR UPDATE:
START TRANSACTION;
SELECT units_in_stock FROM products WHERE product_id = 17 FOR UPDATE; -- others now wait
UPDATE products SET units_in_stock = units_in_stock - 1 WHERE product_id = 17;
COMMIT;If two transactions each wait for a lock the other holds, InnoDB detects the deadlock, rolls one of them back and returns error 1213; the application should simply retry it.
Tip: Keep transactions short. A transaction left open while waiting for user input holds locks and keeps old row versions alive, slowing everyone down.
Test yourself
What does ROLLBACK do?
- Deletes the table
- Undoes all changes since the transaction started
- Undoes only the last statement
- Commits and closes the connection
What happens to an open transaction when you run CREATE TABLE?
- Nothing
- It is rolled back
- It is committed implicitly
- The CREATE TABLE fails
What is InnoDB's default isolation level?
- READ UNCOMMITTED
- READ COMMITTED
- REPEATABLE READ
- SERIALIZABLE