Rollback Sql in SQL
? ROLLBACK in SQL
The ROLLBACK statement is used to undo changes made in a transaction before they are committed. It helps maintain data integrity by reverting data to its previous state.
? Syntax:
ROLLBACK;? When to Use:
If an error occurs during a transaction
If you want to cancel pending changes
To test data manipulation safely
? Example with Transaction:
BEGIN;UPDATE accounts SET balance = balance - 500 WHERE account_id = 1;UPDATE accounts SET balance = balance + 500 WHERE account_id = 2;-- Something goes wrongROLLBACK; -- This undoes both updates? Example in MySQL:
START TRANSACTION;DELETE FROM employees WHERE emp_id = 101;-- Oops! Wrong IDROLLBACK;? Example in SQL Server:
BEGIN TRANSACTION;UPDATE orders SET status = 'Canceled' WHERE order_id = 5;-- Undo itROLLBACK TRANSACTION;? Notes:
Works only if autocommit is off (or inside explicit transaction).
Must be issued before
COMMIT; otherwise, changes are saved and cannot be rolled back.
? Related Commands:
| Command | Description |
|---|---|
BEGIN or START TRANSACTION | Start a transaction |
COMMIT | Save all changes in transaction |
ROLLBACK | Undo all changes since transaction started |
Need a full transaction flow with error handling?