0
0
MySQLquery~5 mins

AVG function in MySQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: AVG function
O(n)
Understanding Time Complexity

We want to understand how the time to calculate an average changes as the data grows.

How does the AVG function's work time grow when there are more rows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


SELECT AVG(salary) FROM employees;
    

This query calculates the average salary from all rows in the employees table.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Scanning each row to add the salary value.
  • How many times: Once for every row in the employees table.
How Execution Grows With Input

As the number of rows grows, the work to add all salaries grows too.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with the number of rows.

Final Time Complexity

Time Complexity: O(n)

This means the time to calculate the average grows in a straight line with the number of rows.

Common Mistake

[X] Wrong: "AVG is instant no matter how many rows there are."

[OK] Correct: The database must look at every row to add values before dividing, so more rows mean more work.

Interview Connect

Knowing how aggregate functions like AVG scale helps you explain query performance clearly and confidently.

Self-Check

"What if we added a WHERE clause to limit rows? How would the time complexity change?"