ABS and MOD functions in SQL - Time & Space Complexity
We want to understand how the time it takes to run ABS and MOD functions changes as we use them on more data.
How does the work grow when we apply these functions to many rows?
Analyze the time complexity of the following code snippet.
SELECT
ABS(salary) AS absolute_salary,
MOD(employee_id, 10) AS mod_result
FROM employees;
This query calculates the absolute value of salaries and the remainder when employee IDs are divided by 10 for every employee.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying ABS and MOD functions to each row in the employees table.
- How many times: Once for each employee row.
Each row requires a fixed amount of work to compute ABS and MOD. So, as the number of rows grows, the total work grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 function calls |
| 100 | 200 function calls |
| 1000 | 2000 function calls |
Pattern observation: The total work grows in a straight line with the number of rows.
Time Complexity: O(n)
This means the time to run the query grows directly with the number of rows processed.
[X] Wrong: "ABS and MOD functions take the same time no matter how many rows there are."
[OK] Correct: Each row needs its own calculation, so more rows mean more total work.
Understanding how simple functions like ABS and MOD scale helps you explain query performance clearly and confidently.
"What if we added a nested query that calls ABS and MOD multiple times per row? How would the time complexity change?"