← Back to Chapters

MySQL ROLLBACK

↩️ MySQL ROLLBACK

? Quick Overview

ROLLBACK is a Transaction Control Language (TCL) command used in MySQL to undo changes made in the current transaction. It restores the database to the last committed state and is mainly used to prevent unwanted data changes.

? Key Concepts

  • Works only with transactional storage engines like InnoDB
  • Undoes INSERT, UPDATE, and DELETE operations
  • Cannot rollback after COMMIT
  • DDL statements like CREATE or DROP auto-commit

? Syntax & Theory

A transaction is a sequence of SQL statements executed as a single logical unit. If something goes wrong, ROLLBACK reverts all changes made during the transaction.

? View Code Example
-- Start a new transaction
START TRANSACTION;

-- Insert a new record
INSERT INTO accounts (name, balance)
VALUES ('Rahul', 5000);

-- Undo the transaction
ROLLBACK;

? Live Output / Explanation

What happens?

  • The record for Rahul is temporarily added
  • ROLLBACK cancels the insert operation
  • No data is permanently saved in the table

? Tips & Best Practices

  • Always use transactions for critical data changes
  • Verify engine type using SHOW TABLE STATUS
  • Use ROLLBACK during testing and debugging
  • Combine with SAVEPOINT for partial rollbacks

? Try It Yourself

  1. Create a table with InnoDB engine
  2. Start a transaction
  3. Insert multiple rows
  4. Execute ROLLBACK
  5. Verify that no rows were saved