Aggregate with NULL handling in SQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
We want to understand how the time to calculate aggregates changes as the data grows.
Specifically, how handling NULL values affects the work done.
Analyze the time complexity of the following SQL query.
SELECT department, AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING AVG(salary) IS NOT NULL;
This query calculates the average salary per department, ignoring NULL salaries.
Look for repeated work done as data grows.
- Primary operation: Scanning each employee row once to compute averages.
- How many times: Once per row in the employees table.
As the number of employees grows, the work to compute averages grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 scans and calculations |
| 100 | 100 scans and calculations |
| 1000 | 1000 scans and calculations |
Pattern observation: Doubling the rows roughly doubles the work.
Time Complexity: O(n)
This means the time grows directly with the number of rows processed.
[X] Wrong: "Handling NULL values makes the query slower by a lot because it adds extra loops."
[OK] Correct: The NULL check happens during the single scan of each row, so it does not add extra passes over the data.
Understanding how aggregate queries scale helps you explain performance in real projects.
"What if we added a WHERE clause filtering rows before aggregation? How would that affect time complexity?"
Practice
NULL values in any column?Solution
Step 1: Understand COUNT(*) behavior
COUNT(*) counts every row in the table regardless of NULL values in any column.Step 2: Compare with COUNT(column_name)
COUNT(column_name) counts only rows where the specified column is NOT NULL.Final Answer:
COUNT(*) -> Option BQuick Check:
COUNT(*) counts all rows including NULLs [OK]
- Thinking COUNT(column) counts all rows
- Confusing SUM with COUNT
- Assuming AVG counts NULLs
sales?Solution
Step 1: Understand COALESCE usage
COALESCE(sales, 0) replaces NULL values in sales with 0 before summing.Step 2: Check other options
SUM(sales) ignores NULLs, NULLIF returns NULL if sales=0, ISNULL(sales) is incomplete syntax.Final Answer:
SUM(COALESCE(sales, 0)) -> Option CQuick Check:
Use COALESCE to replace NULLs before aggregation [OK]
- Using SUM(sales) and expecting NULLs counted as zero
- Confusing NULLIF with COALESCE
- Using ISNULL without second argument
orders with column discount containing values (10, NULL, 10, NULL, 15), what is the result of this query?SELECT AVG(COALESCE(discount, 0)) FROM orders;
Solution
Step 1: Replace NULLs with 0 using COALESCE
Values become 10, 0, 10, 0, 15.Step 2: Calculate average of these values
Sum = 10 + 0 + 10 + 0 + 15 = 35; Count = 5; Average = 35 / 5 = 7.Final Answer:
7 -> Option AQuick Check:
COALESCE replaces NULLs, AVG includes zeros [OK]
- Ignoring NULLs and averaging only non-NULL values
- Assuming AVG ignores zeros
- Miscounting number of rows
score column:SELECT COUNT(score) + COUNT(NULL) FROM results;
Solution
Step 1: Understand COUNT(NULL) behavior
COUNT(NULL) always returns 0 because the NULL expression is always NULL and thus never counted.Step 2: Analyze COUNT(score)
COUNT(score) counts only non-NULL values in score column, not all rows.Final Answer:
COUNT(NULL) returns 0 -> Option DQuick Check:
COUNT(NULL) always returns 0 [OK]
- Thinking COUNT(NULL) counts NULLs
- Assuming COUNT(column) counts NULLs
- Adding COUNT(NULL) to count rows
employees with a nullable bonus column. You want to calculate the total bonus, treating NULL as zero, but only for employees with a salary above 50000. Which query correctly does this?Solution
Step 1: Use COALESCE to treat NULL bonus as zero
SUM(COALESCE(bonus, 0)) replaces NULL bonuses with 0 before summing.Step 2: Filter employees with salary > 50000
The WHERE clause correctly filters rows before aggregation.Step 3: Check query syntax
SELECT SUM(COALESCE(bonus, 0)) FROM employees WHERE salary > 50000; has correct syntax.Final Answer:
SELECT SUM(COALESCE(bonus, 0)) FROM employees WHERE salary > 50000; -> Option AQuick Check:
Use COALESCE in SUM and filter with WHERE [OK]
- Placing WHERE clause after FROM incorrectly
- Not using COALESCE to handle NULLs
- Filtering on COALESCE(salary, 0) unnecessarily
