MySQL — Having
Basic HAVING
SELECT category, COUNT(*) as count
FROM products
GROUP BY category
HAVING count > 10;
HAVING vs WHERE
-- WHERE filters before grouping
SELECT category, COUNT(*) as count
FROM products
WHERE price > 100
GROUP BY category;
-- HAVING filters after grouping
SELECT category, COUNT(*) as count
FROM products
GROUP BY category
HAVING count > 10;
HAVING Examples
-- Categories with average price > 500
SELECT category, AVG(price) as avg_price
FROM products
GROUP BY category
HAVING avg_price > 500;
-- Users with more than 5 orders
SELECT user_id, COUNT(*) as order_count
FROM orders
GROUP BY user_id
HAVING order_count > 5;
-- Departments with total salary > 100000
SELECT department, SUM(salary) as total_salary
FROM employees
GROUP BY department
HAVING total_salary > 100000;
-- Months with sales > 10000
SELECT
MONTH(order_date) as month,
SUM(total) as total_sales
FROM orders
GROUP BY MONTH(order_date)
HAVING total_sales > 10000;
Mini Practice
Write MySQL code that:
- Uses HAVING with COUNT
- Uses HAVING with AVG
- Combines WHERE and HAVING
- Filters grouped data
Up Next
Next: Learn about Distinct values.
Related Topics
Frequently Asked Questions about Having
What is Having in MySQL?
Having is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Having?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Having.
Why is Having important in MySQL?
Having is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.