Why transactions are needed in SQL - Performance Analysis
We want to understand how the time to complete a group of database actions changes as the number of actions grows.
Specifically, we ask: How does using transactions affect the time it takes to run multiple related operations?
Analyze the time complexity of the following SQL transaction.
BEGIN 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 as one single unit of work.
Look for repeated steps or loops in the transaction.
- Primary operation: Two update commands inside one transaction.
- How many times: Each update runs once per transaction.
As the number of operations inside a transaction grows, the total time grows roughly in direct proportion.
| Input Size (number of operations) | Approx. Operations |
|---|---|
| 2 | 2 updates + transaction overhead |
| 10 | 10 updates + transaction overhead |
| 100 | 100 updates + transaction overhead |
Pattern observation: Time grows linearly as more operations are added inside the transaction.
Time Complexity: O(n)
This means the time to complete the transaction grows directly with the number of operations inside it.
[X] Wrong: "Transactions make the operations run instantly or in constant time regardless of size."
[OK] Correct: Transactions group operations but each operation still takes time, so total time grows with the number of operations.
Understanding how transactions affect time helps you explain why grouping operations is useful but still costs time as work grows.
"What if we added rollback steps inside the transaction? How would that affect the time complexity?"