📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials MySQL MySQL Transactions

MySQL Transactions

5 min read Quiz at the end
Wrap related SQL statements in a transaction with START TRANSACTION, COMMIT, and ROLLBACK.

Transactions

START TRANSACTION;

-- Transfer money: deduct from Alice, add to Bob
UPDATE accounts SET balance = balance - 100 WHERE user_id = 1;
UPDATE accounts SET balance = balance + 100 WHERE user_id = 2;

-- Insert audit record
INSERT INTO audit_log (action, amount) VALUES ('transfer', 100);

COMMIT;   -- save all changes

-- On error:
ROLLBACK; -- undo all changes

-- Savepoints
START TRANSACTION;
INSERT INTO orders (user_id, total) VALUES (1, 50.00);
SAVEPOINT after_order;
INSERT INTO order_items (order_id, product_id) VALUES (LAST_INSERT_ID(), 5);
ROLLBACK TO SAVEPOINT after_order;  -- undo items only
COMMIT;

-- Isolation levels
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
-- READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE
Topic Quiz · 1 questions

Test your understanding before moving on

1. What does ROLLBACK do in a transaction?
💡 ROLLBACK reverts all statements in the current transaction that have not been committed.