0
0
SQLquery~5 mins

ABS and MOD functions in SQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: ABS and MOD functions
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

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
1020 function calls
100200 function calls
10002000 function calls

Pattern observation: The total work grows in a straight line with the number of rows.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the query grows directly with the number of rows processed.

Common Mistake

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

Interview Connect

Understanding how simple functions like ABS and MOD scale helps you explain query performance clearly and confidently.

Self-Check

"What if we added a nested query that calls ABS and MOD multiple times per row? How would the time complexity change?"