Q.What is a transaction in a database? Explain the terms COMMIT and ROLLBACK with an example of when each is used.
A transaction is a logical unit of work made up of one or more SQL statements that is treated as a single, indivisible operation — either all of its statements take effect or none of them does. The standard example is a bank transfer: money must be subtracted from one account and added to another, and both must happen or neither should.
A transaction is normally begun with START TRANSACTION; and ends in one of two ways:
-
COMMITmakes all the changes of the transaction permanent. It is used once we are sure the changes are correct; after a commit they are saved and cannot be undone by a rollback. For example, after successfully raising every Sales employee's salary and checking the result, we runCOMMIT;. -
ROLLBACKundoes all the changes made since the transaction began, returning the database to its earlier state. It is used when something goes wrong or a mistake is noticed. For example, if a wrongDELETEremoved the Sales employees, runningROLLBACK;before committing restores them.
START TRANSACTION;
UPDATE Employee SET Salary = Salary + 2000 WHERE Dept = 'Sales';
COMMIT; -- change kept permanently
START TRANSACTION;
DELETE FROM Employee WHERE Dept = 'Sales';
ROLLBACK; -- change undone, rows restored
A transaction is a logical unit of work whose one-or-more statements are all applied or all cancelled together. COMMIT makes all its changes permanent (used when the work is correct); ROLLBACK undoes all changes made since the transaction began (used when a mistake or failure occurs). A committed transaction cannot be rolled back.
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.