COMMIT and ROLLBACK are two key transaction control commands in SQL that ensure data consistency by managing how and when changes made to the database become permanent.
When I perform operations like INSERT, UPDATE, or DELETE, the changes are made temporarily โ theyโre not permanent until I explicitly COMMIT the transaction. So, COMMIT is used to save all the changes made during the current transaction.
BEGIN TRANSACTION;
UPDATE Employees
SET Salary = Salary * 1.10
WHERE Department = 'Sales';
COMMIT;
Here, once the COMMIT is executed, the 10% salary increase for all Sales employees is permanently applied to the database.
On the other hand, ROLLBACK is used to undo changes made in the current transaction if something goes wrong โ like a wrong condition, an unexpected error, or data validation failure.
For instance:
BEGIN TRANSACTION;
UPDATE Employees
SET Salary = Salary * 1.10
WHERE Department = 'Sales';
-- Suppose an error is found, or the condition was wrong
ROLLBACK;
In this case, the ROLLBACK command cancels the update, bringing the data back to its original state before the transaction began.
In a practical project, I applied this concept during a financial data load process. We had to insert hundreds of payment records, and if even one record failed due to data integrity issues, we used ROLLBACK to revert all changes โ ensuring there were no partial or inconsistent updates.
A key challenge Iโve faced is handling transactions in long-running processes โ if you keep transactions open for too long without committing, it can lock tables and affect other users. So I make sure to commit in smaller batches wherever possible.
To summarize, COMMIT makes changes permanent, while ROLLBACK undoes them, helping maintain accuracy and consistency of data during critical operations.
