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