Why transactions ensure data integrity in MySQL - Performance Analysis
We want to understand how the time to complete a transaction changes as the amount of data or operations grows.
How does using transactions affect the time it takes to keep data safe and correct?
Analyze the time complexity of the following transaction in MySQL.
START TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
This code moves money from one account to another safely using a transaction.
Look for repeated actions that take time.
- Primary operation: Two update statements inside a transaction.
- How many times: Each update runs once per transaction.
The time depends mostly on how many rows each update touches.
| Input Size (rows affected) | Approx. Operations |
|---|---|
| 1 | Few operations for two updates |
| 100 | About 100 times more work for each update |
| 1000 | About 1000 times more work for each update |
Pattern observation: Time grows roughly in direct proportion to the number of rows updated.
Time Complexity: O(n)
This means the time to complete the transaction grows linearly with the number of rows affected.
[X] Wrong: "Transactions always take the same time no matter how much data changes."
[OK] Correct: The more rows the transaction updates, the longer it takes because each row needs to be checked and changed safely.
Understanding how transactions scale helps you explain how databases keep data safe without slowing down too much as data grows.
"What if the transaction included a loop updating many rows one by one? How would that change the time complexity?"