Transaction
Last updated
Last updated
Suppose we have a banking system and two clients Alice and Bob. Alice wants to send $100 to Bob. This action can be subdivided into two parts:
Deduct $100 from Alice's account.
Add $100 to Bob's account.
But here is the problem: if step 1 succeeds and step 2 fails, then Alice will lose $100 and Bob will get nothing. We need step 1 and step 2 to be an atomic unit: if step 2 fails, then step 1 must fail as well. To overcome this barrier, MySQL implemented transaction.
Transactions are atomic units of work that can be committed or rolled back. When a transaction makes multiple changes to the database, either all the changes succeed when the transaction is committed, or all the changes are undone when the transaction is rolled back.
Since MySQL > 5.4, the default storage engine is InnoDB. InnoDB supports transaction.
Let there be a table tb with the following entries:
Start a new transaction:
Delete all entries from tb:
Verify that all entries were deleted:
Now, you can either revert the deletion:
or make the deletion permanent:
Auto commit is turned on by default. Turn it off:
This is same as starting a transaction session. Or turn it back on: