← Back to Chapters

MySQL SAVEPOINT

? MySQL SAVEPOINT

? Quick Overview

SAVEPOINT is a transactional command in MySQL that allows you to mark a point within a transaction. You can roll back to this point without undoing the entire transaction.

? Key Concepts

  • SAVEPOINT works only inside a transaction
  • Used with COMMIT and ROLLBACK
  • Allows partial rollback of data changes
  • Improves control in complex transactions

? Syntax / Theory

A SAVEPOINT creates a named checkpoint in the current transaction. You can roll back to this checkpoint anytime before committing.

? View Code Example
-- Create a savepoint inside a transaction
SAVEPOINT sp1;

? Code Example(s)

? View Code Example
-- Start transaction and create savepoints
START TRANSACTION;
INSERT INTO orders VALUES (1,'Laptop');
SAVEPOINT sp1;
INSERT INTO orders VALUES (2,'Mobile');
SAVEPOINT sp2;
INSERT INTO orders VALUES (3,'Tablet');

? Live Output / Explanation

If an error occurs after inserting the third record, you can roll back only to sp2 or sp1 instead of cancelling the entire transaction.

? View Code Example
-- Rollback to a specific savepoint
ROLLBACK TO sp2;

✅ Tips & Best Practices

  • Use meaningful savepoint names
  • Do not overuse savepoints unnecessarily
  • Always COMMIT after successful operations
  • SAVEPOINT is useful in multi-step transactions

? Try It Yourself

  • Create a transaction with three savepoints
  • Rollback to different savepoints and observe results
  • Commit after rolling back to a savepoint