AVG function in MySQL - Time & Space 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?
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 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.
As the number of rows grows, the work to add all salaries grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of rows.
Time Complexity: O(n)
This means the time to calculate the average grows in a straight line with the number of rows.
[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.
Knowing how aggregate functions like AVG scale helps you explain query performance clearly and confidently.
"What if we added a WHERE clause to limit rows? How would the time complexity change?"