</>
Skip to content
MySQL lessons (45/48)

MySQL — Transactions

Basic Transaction

START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

ROLLBACK

START TRANSACTION;
DELETE FROM orders WHERE status = 'cancelled';
ROLLBACK; -- Undo the delete

SAVEPOINT

START TRANSACTION;
INSERT INTO orders (id, total) VALUES (1, 100);
SAVEPOINT sp1;
INSERT INTO order_items (order_id, product) VALUES (1, 'Widget');
ROLLBACK TO sp1; -- Only undo the order_items insert
COMMIT; -- Only the orders insert is saved

Transaction Properties (ACID)

PropertyDescription
AtomicityAll operations succeed or none do
ConsistencyData remains valid after transaction
IsolationConcurrent transactions don't interfere
DurabilityCommitted data survives crashes

Auto-Commit

MySQL auto-commits each statement by default. Disable it:

SET autocommit = 0;
-- Statements are not committed until COMMIT
COMMIT;
SET autocommit = 1;

Transaction with Error Handling

DELIMITER //
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        ROLLBACK;
        SELECT 'Error occurred, rolled back' AS result;
    END;

    START TRANSACTION;
    UPDATE accounts SET balance = balance - 500 WHERE id = 1;
    UPDATE accounts SET balance = balance + 500 WHERE id = 2;
    COMMIT;
    SELECT 'Transfer successful' AS result;
END //
DELIMITER ;

Mini Practice

Write SQL code that:

  1. Starts a transaction and commits it
  2. Starts a transaction and rolls it back
  3. Uses SAVEPOINT and ROLLBACK TO
  4. Disables auto-commit

Up Next

Continue with Prepared Statements — efficient parameterized queries.

Related Topics

Frequently Asked Questions about Transactions

What is Transactions in MySQL?

Transactions is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Transactions?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Transactions.

Why is Transactions important in MySQL?

Transactions is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.