UPDATE with WHERE condition in SQL - Time & Space Complexity
When we update data in a database using a condition, it takes time to find which rows to change.
We want to know how the time needed grows as the data grows.
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 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of rows.
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 rows that match, so it takes the same time no matter how big the table is."
[OK] Correct: The database still looks at every row to find matches, so more rows mean more work.
Understanding how updates scale helps you explain database behavior clearly and shows you know what happens behind the scenes.
"What if we add an index on the department column? How would the time complexity change?"