HAVING — Filtering Groups
WHERE filters rows before grouping. HAVING filters the groups after — understanding the difference is essential.
HAVING is to groups what WHERE is to rows. Use it to keep only the groups that meet a condition.
EXERCISE
1HAVING — Filtering Groups
HAVING filters the result of GROUP BY. Where WHERE filters individual rows, HAVING filters entire groups — and it runs after aggregation.
The WHERE vs HAVING distinction:
-- WHERE: filters rows BEFORE grouping
-- HAVING: filters groups AFTER grouping
-- Find categories where average price > 500:
SELECT category, AVG(price) AS avg_price
FROM products
GROUP BY category
HAVING AVG(price) > 500; -- ✓ correct — filters the groups
-- This would ERROR:
WHERE AVG(price) > 500; -- ✗ wrong — aggregate not allowed in WHERE
Basic HAVING:
-- Customers who have placed more than 3 orders:
SELECT customer_id, COUNT(*) AS order_count
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 3
ORDER BY order_count DESC;
HAVING with multiple conditions:
-- Departments with more than 5 employees AND average salary > 60000:
SELECT
department,
COUNT(*) AS headcount,
AVG(salary) AS avg_salary
FROM employees
GROUP BY department
HAVING COUNT(*) > 5
AND AVG(salary) > 60000
ORDER BY avg_salary DESC;
WHERE and HAVING together:
-- Active products, grouped by category, keeping only categories
-- where average price exceeds 300:
SELECT
category,
COUNT(*) AS product_count,
AVG(price) AS avg_price
FROM products
WHERE is_active = 1 -- filter individual rows first
GROUP BY category
HAVING AVG(price) > 300 -- then filter groups
ORDER BY avg_price DESC;
Pro Tip: You can use either the aggregate expression
HAVING COUNT(*) > 5or an aliasHAVING order_count > 5in MySQL. Using the expression is more portable across databases.
EXERCISE
2HAVING vs WHERE — When to Use Each
Knowing whether to use WHERE or HAVING is a fundamental SQL skill. The rule is simple: if the condition involves an aggregate function, use HAVING. Otherwise, use WHERE.
Decision rule:
Does the condition use COUNT, SUM, AVG, MIN, or MAX?
YES → use HAVING
NO → use WHERE (it''s faster — rows filtered before grouping)
Side-by-side comparison:
-- WRONG — will error:
SELECT department, AVG(salary)
FROM employees
WHERE AVG(salary) > 60000 -- ✗ aggregate in WHERE
GROUP BY department;
-- CORRECT:
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 60000; -- ✓ aggregate in HAVING
-- WRONG (inefficient — filters after grouping):
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING department = 'Engineering'; -- ✗ works but wasteful
-- CORRECT (efficient — filters rows before grouping):
SELECT department, AVG(salary)
FROM employees
WHERE department = 'Engineering' -- ✓ filter first
GROUP BY department;
Best practice — both together:
-- Active employees only, group by department,
-- show departments where avg salary > 50k, order by avg salary:
SELECT
department,
COUNT(*) AS headcount,
ROUND(AVG(salary), 0) AS avg_salary
FROM employees
WHERE is_active = 1 -- WHERE: filter rows (no aggregate)
GROUP BY department
HAVING AVG(salary) > 50000 -- HAVING: filter groups (aggregate)
ORDER BY avg_salary DESC;
Pro Tip: Putting a non-aggregate condition in HAVING instead of WHERE is not wrong — it works — but it wastes work. The database processes all rows into groups first, then discards them. WHERE discards them early, which is faster.
EXERCISE
3Combining GROUP BY, HAVING, and ORDER BY
The real power of aggregation comes from combining all three. These three clauses together let you answer nearly any "how many" or "how much" business question.
Full GROUP BY pattern:
SELECT column, aggregate_function(column) AS alias
FROM table
WHERE row_condition -- runs first, filters rows
GROUP BY column -- groups remaining rows
HAVING group_condition -- filters groups
ORDER BY alias DESC -- sorts result
LIMIT n; -- caps rows returned
Real-world example — top customers:
-- Top 10 customers by total spend (only completed orders, min 2 orders):
SELECT
c.name,
COUNT(o.id) AS order_count,
SUM(o.total) AS total_spent,
AVG(o.total) AS avg_order
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'completed'
GROUP BY c.id, c.name
HAVING COUNT(o.id) >= 2
ORDER BY total_spent DESC
LIMIT 10;
Product performance summary:
-- Categories with more than 10 products and avg rating above 4.0:
SELECT
category,
COUNT(*) AS product_count,
ROUND(AVG(price), 2) AS avg_price,
ROUND(AVG(rating), 1) AS avg_rating,
SUM(stock_qty) AS total_stock
FROM products
WHERE is_active = 1
GROUP BY category
HAVING COUNT(*) > 10
AND AVG(rating) >= 4.0
ORDER BY avg_rating DESC, product_count DESC;
Pro Tip: Master this full pattern — SELECT + FROM + WHERE + GROUP BY + HAVING + ORDER BY + LIMIT. It is the template for almost every reporting and analytics query you will ever write.
