Junior — Middle
Can you explain what the ROLLBACK operation means in the context of SQL and how it affects transactions?
sobes.tech AI
Answer from AI
The ROLLBACK operation in SQL is used to undo all changes made in the current transaction and revert the database to the state before this transaction began.
When a transaction starts, it can include several operations (INSERT, UPDATE, DELETE, etc.). If an error occurs during execution or if changes need to be canceled, ROLLBACK is performed, which cancels all changes made within this transaction.
Example:
BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
-- If something goes wrong
ROLLBACK;
After ROLLBACK, the balance in the accounts table remains unchanged, as it was before the transaction started.
Thus, ROLLBACK ensures data integrity by allowing the cancellation of partially executed operations in case of errors or other reasons.