0
0
SQLquery~5 mins

AVG function in SQL - Time & Space Complexity

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

When we use the AVG function in SQL, the database calculates the average value of a column. Understanding how long this takes helps us know how the query performs as data grows.

We want to find out how the time to get the average changes when the number of rows increases.

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: The database scans each row in the employees table once to add up the salaries.
  • How many times: Once for every row in the table.
How Execution Grows With Input

As the number of rows grows, the database must look at more salaries to add them up before dividing.

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

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

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 because it's just one function call."

[OK] Correct: The AVG function must look at every row's value to add them up before dividing, so more rows mean more work.

Interview Connect

Knowing how aggregate functions like AVG scale with data size helps you explain query performance clearly and confidently in real situations.

Self-Check

"What if we added a WHERE clause to filter rows before calculating AVG? How would the time complexity change?"