AVG function in SQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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.
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: 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.
As the number of rows grows, the database must look at more salaries to add them up before dividing.
| 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. Double the rows, double the work.
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 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.
Knowing how aggregate functions like AVG scale with data size helps you explain query performance clearly and confidently in real situations.
"What if we added a WHERE clause to filter rows before calculating AVG? How would the time complexity change?"
Practice
AVG() function do?Solution
Step 1: Understand the purpose of AVG()
The AVG() function is designed to calculate the average (mean) of numeric values in a column.Step 2: Compare with other aggregate functions
Unlike COUNT(), MAX(), or SUM(), AVG() specifically returns the average value.Final Answer:
Calculates the average value of a numeric column -> Option AQuick Check:
AVG() = average calculation [OK]
- Confusing AVG() with COUNT()
- Thinking AVG() sums values without dividing
- Assuming AVG() works on non-numeric columns
Employees?Solution
Step 1: Recall correct AVG() syntax
The AVG() function requires parentheses around the column name: AVG(column_name).Step 2: Check each option
Correct syntax uses AVG(salary) with parentheses. Missing parentheses, AVERAGE(salary), or salary AVG() cause syntax errors.Final Answer:
SELECT AVG(salary) FROM Employees; -> Option BQuick Check:
AVG(column) uses parentheses [OK]
- Omitting parentheses in AVG()
- Using wrong function name like AVERAGE()
- Placing AVG() after column name incorrectly
Scores with values:Score90
80
NULL
70
What will the query
SELECT AVG(Score) FROM Scores; return?Solution
Step 1: Identify values considered by AVG()
AVG() ignores NULL values, so it averages 90, 80, and 70.Step 2: Calculate the average
(90 + 80 + 70) / 3 = 240 / 3 = 80.Final Answer:
80 -> Option CQuick Check:
AVG ignores NULL, average = 80 [OK]
- Including NULL as zero in average
- Returning NULL if any NULL exists
- Summing values without dividing
SELECT AVG(price) FROM Products WHERE price > 0;It returns NULL even though there are products with price 0 and above. What is the likely problem?
Solution
Step 1: Analyze the WHERE clause condition
The condition price > 0 excludes prices equal to zero, so only prices greater than zero are included.Step 2: Consider data and NULL result
If no prices are greater than zero, the filtered set is empty, so AVG() returns NULL.Final Answer:
The WHERE clause excludes all rows because price > 0 filters out zero prices -> Option AQuick Check:
Empty filtered rows cause AVG() to return NULL [OK]
- Thinking AVG() can't use WHERE
- Assuming AVG() needs GROUP BY always
- Ignoring that empty sets return NULL
Sales with columns Region and Amount. How do you write a query to find the average sales amount per region, excluding regions with no sales?Solution
Step 1: Group sales by region
Use GROUP BY Region to calculate average per region.Step 2: Exclude regions with no sales
Regions with no sales have AVG(Amount) as NULL, so use HAVING AVG(Amount) IS NOT NULL to filter them out.Final Answer:
SELECT Region, AVG(Amount) FROM Sales GROUP BY Region HAVING AVG(Amount) IS NOT NULL; -> Option DQuick Check:
GROUP BY + HAVING filters NULL averages [OK]
- Using WHERE after GROUP BY (invalid syntax)
- Not filtering NULL averages with HAVING
- Filtering rows before grouping instead of after
