HAVING clause for filtering groups 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 run a query with a HAVING clause changes as the data grows.
Specifically, how filtering groups after aggregation affects the work done.
Analyze the time complexity of the following code snippet.
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 5;
This query groups employees by their department and then filters to keep only departments with more than 5 employees.
- Primary operation: Scanning all employee rows once to group them by department.
- How many times: Once for all rows (n times, where n is number of employees).
- Secondary operation: Checking each group to apply the HAVING filter.
- How many times: Once per group (g times, where g is number of departments).
The query scans every employee once, so if employees double, work roughly doubles.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row scans + groups checked |
| 100 | About 100 row scans + groups checked |
| 1000 | About 1000 row scans + groups checked |
Pattern observation: The main work grows roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of rows in the table.
[X] Wrong: "The HAVING clause makes the query run slower by checking every row again."
[OK] Correct: The HAVING clause only filters after grouping, so it checks groups, not every row again.
Understanding how grouping and filtering groups affects query time helps you explain database performance clearly and confidently.
"What if we added an ORDER BY clause after HAVING? How would the time complexity change?"
Practice
What is the main purpose of the HAVING clause in SQL?
Solution
Step 1: Understand the role of
TheGROUP BYGROUP BYclause groups rows based on column values.Step 2: Identify the purpose of
HAVINGHAVINGfilters these groups using aggregate functions likeSUMorCOUNT.Final Answer:
To filter groups created byGROUP BYbased on aggregate conditions -> Option CQuick Check:
HAVINGfilters groups, not rows [OK]
- Confusing HAVING with WHERE clause
- Using HAVING without GROUP BY
- Thinking HAVING sorts data
Which of the following is the correct syntax to filter groups with HAVING?
SELECT department, COUNT(*) FROM employees GROUP BY department _______ COUNT(*) > 5;
Solution
Step 1: Identify filtering clause after grouping
AfterGROUP BY, filtering groups requiresHAVING, notWHERE.Step 2: Confirm correct clause usage
HAVING COUNT(*) > 5filters groups with more than 5 employees.Final Answer:
HAVING -> Option DQuick Check:
Use HAVING after GROUP BY [OK]
- Using WHERE instead of HAVING after GROUP BY
- Placing HAVING before GROUP BY
- Using FILTER keyword which is invalid here
Given the table sales with columns region and amount, what will this query return?
SELECT region, SUM(amount) FROM sales GROUP BY region HAVING SUM(amount) > 1000;
Solution
Step 1: Group sales by region and sum amounts
The query groups rows byregionand calculates totalamountper region.Step 2: Filter groups with total sales > 1000
TheHAVINGclause keeps only regions where the sum is greater than 1000.Final Answer:
All regions with total sales greater than 1000 -> Option AQuick Check:
HAVING filters groups by aggregate sum [OK]
- Thinking HAVING filters individual rows
- Confusing SUM(amount) with amount column
- Assuming syntax error with HAVING
Identify the error in this query:
SELECT category, COUNT(*) FROM products HAVING COUNT(*) > 10 GROUP BY category;
Solution
Step 1: Check order of clauses in SQL
The correct order isGROUP BYfirst, thenHAVING.Step 2: Identify incorrect clause order
The query placesHAVINGbeforeGROUP BY, causing syntax error.Final Answer:
HAVING clause used before GROUP BY -> Option BQuick Check:
GROUP BY before HAVING [OK]
- Placing HAVING before GROUP BY
- Thinking HAVING needs WHERE before it
- Replacing GROUP BY with ORDER BY incorrectly
You have a students table with columns class and score. You want to find classes where the average score is at least 75 and the number of students is more than 10. Which query achieves this?
Solution
Step 1: Group students by class
UseGROUP BY classto group rows by class.Step 2: Filter groups with HAVING using aggregate conditions
UseHAVING AVG(score) >= 75 AND COUNT(*) > 10to keep classes meeting both conditions.Final Answer:
SELECT class, AVG(score), COUNT(*) FROM students GROUP BY class HAVING AVG(score) >= 75 AND COUNT(*) > 10; -> Option AQuick Check:
HAVING filters groups by multiple aggregates [OK]
- Placing HAVING before GROUP BY
- Using WHERE with aggregate functions
- Putting WHERE after GROUP BY
