HAVING clause in MySQL - Time & Space Complexity
When using the HAVING clause in SQL, we want to know how the time to run the query changes as the data grows.
We ask: How does filtering groups after aggregation affect the work the database does?
Analyze the time complexity of the following code snippet.
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;
This query groups employees by department, counts how many are in each, and then keeps only departments with more than 10 employees.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning all employee rows once to group them by department.
- How many times: Once for all rows, then once over each group to apply the HAVING filter.
The database reads each employee row once to count them per department. Then it checks each department group to see if it meets the HAVING condition.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row reads + groups checked |
| 100 | About 100 row reads + groups checked |
| 1000 | About 1000 row reads + groups checked |
Pattern observation: The 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 as the number of rows increases.
[X] Wrong: "HAVING filters rows before grouping, so it reduces the work early."
[OK] Correct: HAVING filters after grouping, so the database must first process all rows to form groups before filtering.
Understanding how HAVING works helps you explain query performance clearly and shows you know how databases handle grouped data.
"What if we replaced HAVING with a WHERE clause before grouping? How would the time complexity change?"
Practice
HAVING clause in SQL?Solution
Step 1: Understand filtering in SQL
TheWHEREclause filters rows before grouping, butHAVINGfilters after groups are formed.Step 2: Identify the role of
HAVINGHAVINGis used to filter groups based on aggregate conditions likeCOUNTorSUM.Final Answer:
To filter groups after aggregation -> Option AQuick Check:
HAVING filters groups, not rows [OK]
- Confusing HAVING with WHERE clause
- Using HAVING without GROUP BY
- Thinking HAVING sorts data
HAVING with GROUP BY in MySQL?Solution
Step 1: Recall correct order of clauses
In SQL,GROUP BYcomes beforeHAVING. The correct order is SELECT -> FROM -> GROUP BY -> HAVING.Step 2: Check each option's syntax
SELECT col1, COUNT(col2) FROM table GROUP BY col1 HAVING COUNT(col2) > 5; correctly placesGROUP BYbeforeHAVINGand includes aggregate function in HAVING condition.Final Answer:
SELECT col1, COUNT(col2) FROM table GROUP BY col1 HAVING COUNT(col2) > 5; -> Option BQuick Check:
GROUP BY before HAVING [OK]
- Placing HAVING before GROUP BY
- Using WHERE with aggregate functions
- Omitting GROUP BY when using HAVING
sales with columns region and amount, what will this query return?SELECT region, SUM(amount) AS total_sales FROM sales GROUP BY region HAVING total_sales > 1000;
Solution
Step 1: Understand the query logic
The query groups rows byregionand sumsamountastotal_sales.Step 2: Apply HAVING condition
It filters groups wheretotal_salesis greater than 1000. Using alias in HAVING is allowed in MySQL.Final Answer:
All regions with total sales greater than 1000 -> Option CQuick Check:
HAVING filters groups by aggregate result [OK]
- Thinking HAVING filters rows, not groups
- Assuming alias can't be used in HAVING in MySQL
- Confusing HAVING with WHERE
SELECT department, COUNT(*) FROM employees HAVING COUNT(*) > 10;
Solution
Step 1: Check for GROUP BY usage
The query uses HAVING with COUNT(*) but does not group bydepartment. HAVING requires GROUP BY to define groups.Step 2: Understand HAVING requirements
HAVING filters groups after aggregation. Without GROUP BY, groups are not defined, causing an error.Final Answer:
Missing GROUP BY clause before HAVING -> Option AQuick Check:
HAVING needs GROUP BY to filter groups [OK]
- Using HAVING without GROUP BY
- Replacing HAVING with WHERE incorrectly
- Assuming COUNT(*) can't be in HAVING
products table with columns category, price, and stock. Write a query to find categories where the average price is above 50 and total stock is at least 100.Which query correctly uses
HAVING to achieve this?Solution
Step 1: Recall correct clause order
The correct order is SELECT -> FROM -> GROUP BY -> HAVING. HAVING filters groups based on aggregate conditions.Step 2: Analyze each option
SELECT category FROM products GROUP BY category HAVING AVG(price) > 50 AND SUM(stock) >= 100; correctly groups bycategoryand uses HAVING with aggregate functionsAVG(price)andSUM(stock).Final Answer:
SELECT category FROM products GROUP BY category HAVING AVG(price) > 50 AND SUM(stock) >= 100; -> Option DQuick Check:
HAVING filters grouped data with aggregate conditions [OK]
- Placing HAVING before GROUP BY
- Using WHERE with aggregate functions
- Omitting GROUP BY when using HAVING
Ready to prove it?
Pass the test and this pattern moves unknown
