BEGIN TRANSACTION syntax in SQL - Time & Space Complexity
We want to understand how the time to run a transaction changes as the amount of work inside it grows.
How does the number of operations inside a transaction affect the total time?
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 between two accounts inside a transaction to keep data safe.
Look for repeated actions that take time.
- Primary operation: Two UPDATE statements inside the transaction.
- How many times: Each UPDATE runs once per transaction in this example.
As the number of UPDATE statements inside the transaction grows, the total work grows too.
| Input Size (number of UPDATEs) | Approx. Operations |
|---|---|
| 2 | 2 UPDATE operations |
| 10 | 10 UPDATE operations |
| 100 | 100 UPDATE operations |
Pattern observation: The total time grows roughly in direct proportion to the number of statements inside the transaction.
Time Complexity: O(n)
This means the time to complete the transaction grows linearly with the number of operations inside it.
[X] Wrong: "A transaction always takes the same time no matter how many operations it has."
[OK] Correct: More operations inside a transaction mean more work, so the time grows with the number of operations.
Understanding how transaction time grows helps you write efficient database code and explain your reasoning clearly in interviews.
"What if we added a loop that runs 100 UPDATE statements inside one transaction? How would the time complexity change?"