0
0
SQLquery~5 mins

Why transactions are needed in SQL - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why transactions are needed
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of operations inside a transaction grows, the total time grows roughly in direct proportion.

Input Size (number of operations)Approx. Operations
22 updates + transaction overhead
1010 updates + transaction overhead
100100 updates + transaction overhead

Pattern observation: Time grows linearly as more operations are added inside the transaction.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete the transaction grows directly with the number of operations inside it.

Common Mistake

[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.

Interview Connect

Understanding how transactions affect time helps you explain why grouping operations is useful but still costs time as work grows.

Self-Check

"What if we added rollback steps inside the transaction? How would that affect the time complexity?"