Step 14
5 min read

ROLLBACK

Learn how to cancel changes - undo button for SQL!

What is ROLLBACK?

ROLLBACK cancels all changes in a transaction. Like "Undo" button.

Simple analogy: Like clicking "Cancel" instead of "Save" - all changes disappear.

Basic Syntax

BEGIN; -- Your changes here ROLLBACK; -- Cancel everything!

Simple Example

BEGIN; UPDATE students SET grade = 'F' WHERE student_id = 1; -- Wait, wrong student! ROLLBACK; -- Cancelled! Grade not changed.

When to Use ROLLBACK

Scenario 1: Made a Mistake

BEGIN; DELETE FROM orders WHERE order_id = 1; -- Oops, wrong order! ROLLBACK; -- Order not deleted!

Scenario 2: Error Occurred

BEGIN; UPDATE accounts SET balance = balance - 100 WHERE user_id = 1; -- OK UPDATE accounts SET balance = balance + 100 WHERE user_id = 999; -- ERROR: user does not exist ROLLBACK; -- First UPDATE cancelled too!

COMMIT vs ROLLBACK

COMMIT: Save changes (permanent) ROLLBACK: Cancel changes (undo)

BEGIN; UPDATE products SET price = 50; -- Option 1: Save it COMMIT; -- Option 2: Cancel it ROLLBACK;

Real Example

BEGIN; UPDATE inventory SET stock = stock - 10 WHERE product_id = 1; UPDATE orders SET status = 'shipped' WHERE order_id = 101; -- Check if everything looks good SELECT * FROM inventory WHERE product_id = 1; -- If good: COMMIT; -- If something wrong: -- ROLLBACK;

Summary

ROLLBACK = Undo all changes

  • Like Cancel button
  • Changes disappear
  • Database goes back to before BEGIN
  • Very useful when you make mistakes

Finished this topic?

Mark it complete to track your progress and maintain your streak!

SkillsetMaster - AI, Web Development & Data Analytics Courses