0
0
MySQLquery~5 mins

BEGIN, COMMIT, ROLLBACK in MySQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: BEGIN, COMMIT, ROLLBACK
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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

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
10About 10 updates processed before commit
100About 100 updates processed before commit
1000About 1000 updates processed before commit

Pattern observation: The time grows roughly in a straight line as more statements 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 statements inside it.

Common Mistake

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

Interview Connect

Understanding how transaction commands scale with workload helps you reason about database performance and reliability in real projects.

Self-Check

"What if we added nested transactions or savepoints? How would the time complexity change?"