UPDATE with WHERE clause in MySQL - Time & Space Complexity
When we update data in a database, the time it takes depends on how many rows we check and change.
We want to know how the work grows as the table gets bigger when using an UPDATE with a WHERE clause.
Analyze the time complexity of the following code snippet.
UPDATE employees
SET salary = salary * 1.1
WHERE department = 'Sales';
This code increases the salary by 10% for all employees in the Sales department.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning rows to check the department value.
- How many times: Once for each row in the employees table.
As the number of employees grows, the database checks more rows to find those in Sales.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the number of rows in the table.
Time Complexity: O(n)
This means the time to update grows in a straight line as the table gets bigger.
[X] Wrong: "The UPDATE only touches the matching rows, so it runs in constant time."
[OK] Correct: The database must check every row to find matches, so the time grows with the table size.
Understanding how updates scale helps you explain database performance clearly and shows you know what happens behind the scenes.
"What if the department column has an index? How would the time complexity change?"