Conditional aggregation pattern in SQL - Time & Space Complexity
We want to understand how the time to run a conditional aggregation query changes as the data grows.
Specifically, how does checking conditions inside aggregation affect performance?
Analyze the time complexity of the following code snippet.
SELECT
department_id,
COUNT(CASE WHEN status = 'active' THEN 1 END) AS active_count,
COUNT(CASE WHEN status = 'inactive' THEN 1 END) AS inactive_count
FROM employees
GROUP BY department_id;
This query counts active and inactive employees per department using conditional aggregation.
- Primary operation: Scanning each row in the employees table once.
- How many times: Once per row, checking conditions and updating counts.
As the number of employees grows, the query checks each row once, applying conditions and counting.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and counts |
| 100 | About 100 checks and counts |
| 1000 | About 1000 checks and counts |
Pattern observation: The work grows directly with the number of rows; doubling rows doubles work.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of rows in the table.
[X] Wrong: "Conditional aggregation makes the query run much slower because it checks multiple conditions per row repeatedly."
[OK] Correct: The query still scans each row only once, checking conditions in a single pass, so the time grows linearly, not exponentially.
Understanding how conditional aggregation scales helps you explain query performance clearly and shows you can reason about data processing efficiently.
"What if we added a nested subquery inside the CASE statements? How would the time complexity change?"
Practice
SUM(CASE WHEN condition THEN value ELSE 0 END)Solution
Step 1: Understand conditional aggregation concept
Conditional aggregation uses CASE inside aggregate functions like SUM or COUNT to selectively include values based on conditions.Step 2: Identify what it achieves
This lets you calculate sums or counts for different conditions in one query without multiple scans.Final Answer:
Calculate sums or counts based on specific conditions within one query -> Option DQuick Check:
Conditional aggregation = selective sums/counts [OK]
- Confusing conditional aggregation with JOIN operations
- Thinking it creates or deletes tables
- Assuming it filters rows outside aggregation
status = 'active' using conditional aggregation?Solution
Step 1: Recall correct CASE syntax inside COUNT
The CASE expression must have WHEN condition THEN value ELSE NULL END for COUNT to count only matching rows.Step 2: Check each option
COUNT(CASE WHEN status = 'active' THEN 1 ELSE NULL END) uses correct CASE syntax with ELSE NULL, so COUNT counts only 'active' rows. COUNT(CASE status = 'active' THEN 1 END) misses WHEN keyword. SUM(CASE WHEN status = 'active' THEN 1 ELSE 0 END) uses SUM, not COUNT. COUNT(IF status = 'active' THEN 1 ELSE 0 END) uses invalid IF syntax.Final Answer:
COUNT(CASE WHEN status = 'active' THEN 1 ELSE NULL END) -> Option AQuick Check:
COUNT + CASE WHEN ... THEN 1 ELSE NULL END [OK]
- Omitting WHEN keyword in CASE
- Using SUM instead of COUNT for counting rows
- Using ELSE 0 which counts zeros as rows
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 the CASE inside SUM
The CASE returns amount if amount > 100, else 0. So only amounts above 100 contribute to the sum.Step 2: Understand GROUP BY effect
The query groups rows by region, summing only big sales (amount > 100) per region.Final Answer:
Sum of sales amounts greater than 100 per region -> Option AQuick Check:
SUM with CASE filters amounts > 100 [OK]
- Thinking it sums all sales, ignoring condition
- Confusing SUM with COUNT
- Assuming it sums small sales instead
SELECT department, COUNT(CASE WHEN salary > 50000 THEN 1 ELSE 0 END) AS high_earners FROM employees GROUP BY department;
Solution
Step 1: Understand COUNT behavior with CASE
COUNT counts all non-NULL values. Here ELSE 0 returns zero, which is counted as a value, so all rows count.Step 2: Identify correct fix
To count only high earners, ELSE should be NULL so those rows are ignored by COUNT.Final Answer:
COUNT counts zeros, so it counts all rows, not just high earners -> Option BQuick Check:
COUNT counts non-NULL, zero is counted [OK]
- Using ELSE 0 causes wrong counts
- Confusing COUNT with SUM
- Ignoring that zero is counted by COUNT
Solution
Step 1: Identify total sales calculation
Total sales is sum of all amounts, so SUM(amount) is correct.Step 2: Identify count of sales above 1000
Counting sales above 1000 can be done by summing 1 for each qualifying row and 0 otherwise, so SUM(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) works.Step 3: Check each option
SELECT product, SUM(amount) AS total_sales, COUNT(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product; uses COUNT with ELSE 0 which counts all rows incorrectly; SELECT product, SUM(CASE WHEN amount > 1000 THEN amount ELSE 0 END) AS total_sales, COUNT(amount) AS big_sales_count FROM sales GROUP BY product; incorrectly sums only amounts above 1000 for total_sales; SELECT product, COUNT(amount) AS total_sales, SUM(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product; swaps SUM and COUNT incorrectly; SELECT product, SUM(amount) AS total_sales, SUM(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product; correctly sums total sales and counts big sales using SUM with CASE.Final Answer:
SELECT product, SUM(amount) AS total_sales, SUM(CASE WHEN amount > 1000 THEN 1 ELSE 0 END) AS big_sales_count FROM sales GROUP BY product; -> Option CQuick Check:
SUM for totals, SUM(CASE) for conditional counts [OK]
- Using COUNT with ELSE 0 which counts all rows
- Summing only filtered amounts for total sales
- Mixing COUNT and SUM incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
