CASE with aggregate functions in SQL - Time & Space Complexity
We want to understand how the time to run a SQL query with CASE inside aggregate functions changes as the data grows.
Specifically, how does the query's work increase when there are more rows to process?
Analyze the time complexity of the following SQL query.
SELECT
department_id,
SUM(CASE WHEN status = 'active' THEN salary ELSE 0 END) AS active_salary,
COUNT(CASE WHEN status = 'inactive' THEN 1 ELSE NULL END) AS inactive_count
FROM employees
GROUP BY department_id;
This query calculates total salary for active employees and counts inactive employees per department.
Look for repeated actions in the query.
- Primary operation: Scanning each row in the employees table once.
- How many times: Once per row, applying the CASE checks and updating sums or counts.
As the number of rows grows, the query does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row checks and updates |
| 100 | About 100 row checks and updates |
| 1000 | About 1000 row checks and updates |
Pattern observation: The work grows directly with the number of rows; doubling rows roughly doubles work.
Time Complexity: O(n)
This means the query's work grows in a straight line with the number of rows it processes.
[X] Wrong: "Using CASE inside aggregates makes the query slower than scanning all rows once."
[OK] Correct: The CASE just adds a quick check per row; the query still scans each row only once, so it doesn't multiply the work.
Understanding how aggregate functions with CASE scale helps you explain query performance clearly and confidently.
"What if we added a nested subquery inside the CASE? How would that affect the time complexity?"
Practice
SELECT SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) FROM users;Solution
Step 1: Understand the CASE inside SUM
The CASE returns 1 for each row where status is 'active', else 0.Step 2: SUM adds all 1s and 0s
SUM counts how many rows have status 'active' by adding 1s.Final Answer:
Counts how many users have status 'active'. -> Option DQuick Check:
SUM(CASE WHEN condition THEN 1 ELSE 0 END) counts matches [OK]
- Thinking SUM adds status values instead of counting
- Confusing ELSE 0 with ELSE NULL
- Assuming it counts non-active users
score is greater than 50 using CASE inside COUNT?Solution
Step 1: Recall COUNT counts non-null values
COUNT counts rows where expression is NOT NULL.Step 2: Use CASE to return 1 for matches, NULL otherwise
CASE WHEN condition THEN 1 END returns 1 or NULL (default ELSE NULL).Final Answer:
SELECT COUNT(CASE WHEN score > 50 THEN 1 END) FROM results; -> Option AQuick Check:
COUNT with CASE returning NULL for no match counts only matches [OK]
- Using ELSE 0 causes COUNT to count all rows
- Omitting WHEN keyword
- Using invalid CASE syntax
sales with columns region and amount, what is the output of this query?SELECT region, SUM(CASE WHEN amount > 100 THEN amount ELSE 0 END) AS big_sales FROM sales GROUP BY region;
Solution
Step 1: Analyze CASE inside SUM
CASE returns amount if > 100, else 0, so only big sales count fully.Step 2: SUM adds these amounts per region
SUM totals amounts > 100 per region, ignoring smaller sales by adding 0.Final Answer:
Sum of sales amounts greater than 100 per region. -> Option BQuick Check:
SUM with CASE filters values conditionally [OK]
- Thinking it counts rows instead of sums amounts
- Ignoring ELSE 0 and expecting NULL filtering
- Confusing greater than with less than
SELECT department, COUNT(CASE department = 'HR' THEN 1 ELSE NULL END) FROM employees GROUP BY department;
Solution
Step 1: Check CASE syntax
CASE requires WHEN before condition; here it's missing.Step 2: Confirm correct syntax
Correct form: CASE WHEN department = 'HR' THEN 1 ELSE NULL END.Final Answer:
Missing WHEN keyword in CASE statement. -> Option AQuick Check:
CASE syntax needs WHEN before condition [OK]
- Omitting WHEN keyword
- Misusing COUNT with CASE
- Incorrect GROUP BY usage
Solution
Step 1: Understand AVG ignores NULLs
AVG calculates average of non-null values only.Step 2: Use CASE to return salary if > 50000, else NULL
This excludes salaries ≤ 50000 from average calculation.Final Answer:
SELECT AVG(CASE WHEN salary > 50000 THEN salary ELSE NULL END) FROM employees; -> Option CQuick Check:
AVG with CASE ELSE NULL excludes unwanted rows [OK]
- Using ELSE 0 includes zeros in average, skewing result
- Omitting WHEN keyword
- Using invalid CASE syntax
Ready to prove it?
Pass the test and this pattern moves unknown
