Commit And Rollback In Sql in SQL
? COMMIT and ROLLBACK in SQL
These two commands are part of transaction control in SQL, used to manage changes made by a series of SQL statements.
1. COMMIT
Saves all changes made in the current transaction permanently to the database.
Once committed, changes cannot be undone by rollback.
Used to finalize a transaction.
Syntax:
COMMIT;Example:
BEGIN TRANSACTION;UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;UPDATE accounts SET balance = balance + 100 WHERE account_id = 2;COMMIT;2. ROLLBACK
Undoes all changes made in the current transaction.
Reverts the database to the state before the transaction began.
Used to cancel or undo changes if an error occurs.
Syntax:
ROLLBACK;Example:
BEGIN TRANSACTION;UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;-- Suppose something goes wrong hereROLLBACK;? Key Points
Transactions group multiple SQL statements into a single unit.
Use
COMMITto make changes permanent.Use
ROLLBACKto discard changes on error or unwanted situations.Some databases start transactions implicitly; others require explicit
BEGIN TRANSACTION.Helps maintain data integrity and consistency.
Want an example showing full transaction control with error handling?