← Back to Chapters

MySQL START TRANSACTION

? MySQL START TRANSACTION

? Quick Overview

START TRANSACTION is used in MySQL to begin a database transaction. A transaction allows you to execute multiple SQL statements as a single logical unit, ensuring data consistency and control over commit or rollback.

? Key Concepts

  • Transaction groups multiple SQL statements together
  • Changes are temporary until committed
  • Rollback can undo changes if something goes wrong
  • Works only with transactional storage engines like InnoDB

? Syntax / Theory

A transaction starts with START TRANSACTION and ends with either COMMIT or ROLLBACK.

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

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

-- Update another record
UPDATE accounts SET balance = balance - 1000 WHERE name = 'Amit';

-- Save all changes permanently
COMMIT;

? Live Output / Explanation

All SQL statements execute successfully and the changes are permanently stored in the database after COMMIT. If any statement fails before commit, you can use ROLLBACK to undo all changes.

? Tips & Best Practices

  • Always use transactions for financial or critical operations
  • Keep transactions short to avoid locking issues
  • Use ROLLBACK during testing to avoid permanent changes
  • Ensure tables use InnoDB engine

? Try It Yourself

  • Start a transaction and insert multiple rows, then rollback
  • Update records inside a transaction and commit them
  • Test behavior with and without commit