You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
A transaction is a sequence of one or more SQL operations that are treated as a single logical unit of work. Either all operations in the transaction succeed (and are committed), or none of them take effect (and are rolled back). Transactions are essential for maintaining data integrity, especially in multi-user environments.
Consider a bank transfer: moving 100 pounds from Account A to Account B requires two operations:
If the system crashes after step 1 but before step 2, the 100 pounds would vanish — the money has been deducted but never added. By wrapping both operations in a transaction, we guarantee that either both happen or neither happens.
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 'A';
UPDATE Accounts SET Balance = Balance + 100 WHERE AccountID = 'B';
COMMIT;
If an error occurs, the database performs a rollback:
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 100 WHERE AccountID = 'A';
-- Error occurs here
ROLLBACK;
-- Both accounts remain unchanged
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.