BEGIN, COMMIT, ROLLBACK in MySQL - Time & Space Complexity
We want to understand how the time taken by transaction commands like BEGIN, COMMIT, and ROLLBACK changes as the amount of work inside the transaction grows.
How does the size of the transaction affect how long these commands take?
Analyze the time complexity of the following code snippet.
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
This code starts a transaction, moves money between two accounts, and then saves the changes permanently.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The database processes each update statement inside the transaction.
- How many times: Once per update statement; the transaction commands themselves do not loop.
As the number of statements inside the transaction grows, the work done before COMMIT or ROLLBACK grows roughly in direct proportion.
| Input Size (number of statements) | Approx. Operations |
|---|---|
| 10 | About 10 updates processed before commit |
| 100 | About 100 updates processed before commit |
| 1000 | About 1000 updates processed before commit |
Pattern observation: The time grows roughly in a straight line as more statements are added inside the transaction.
Time Complexity: O(n)
This means the time to complete the transaction grows directly with the number of statements inside it.
[X] Wrong: "BEGIN, COMMIT, and ROLLBACK always take the same time no matter how many statements are inside."
[OK] Correct: These commands manage the transaction as a whole, so the more work inside, the longer the commit or rollback takes to finalize all changes.
Understanding how transaction commands scale with workload helps you reason about database performance and reliability in real projects.
"What if we added nested transactions or savepoints? How would the time complexity change?"