HAVING Clause in SQL
Introduction
In SQL for data analysis, filtering grouped data is just as important as grouping it. While the WHERE clause filters rows before grouping, the HAVING clause filters data after aggregation. In this lesson, you will learn how to use the HAVING clause in SQL to refine grouped results and generate more meaningful insights.
What is HAVING in SQL
The HAVING clause is used to filter records after applying the GROUP BY clause and aggregate functions. It is mainly used with functions like COUNT, SUM, and AVG.
Basic syntax:
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Difference Between WHERE and HAVING
- WHERE filters rows before grouping
- HAVING filters grouped data after aggregation
Example:
SELECT department, COUNT()
FROM employees
GROUP BY department
HAVING COUNT() > 5;
This query returns only those departments that have more than 5 employees.
Using HAVING with SUM
Example:
SELECT department, SUM(salary)
FROM employees
GROUP BY department
HAVING SUM(salary) > 100000;
This helps identify departments with total salary above a certain threshold.
Using HAVING with AVG
Example:
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 30000;
This shows departments where the average salary is greater than 30000.
Combining WHERE and HAVING
You can use both WHERE and HAVING in the same query.
Example:
SELECT department, COUNT()
FROM employees
WHERE city = ‘Jaipur’
GROUP BY department
HAVING COUNT() > 2;
This first filters employees from Jaipur and then groups them by department.
Why HAVING is Important in Data Analysis
The HAVING clause helps you:
- Filter summarized data
- Focus on meaningful insights
- Create advanced reports
- Analyze grouped trends effectively
Best Practices
- Use HAVING only with GROUP BY
- Avoid using HAVING without aggregation
- Combine with WHERE for better performance
- Keep conditions clear and optimized
Summary
In this lesson, you learned how to use the HAVING clause in SQL to filter grouped data. This is a powerful concept in SQL for data analysis and helps refine your results after aggregation. In the next module, you will start learning SQL joins, which are essential for combining data from multiple tables.
FAQs
1. What is HAVING clause in SQL?
HAVING is used to filter grouped data after applying aggregate functions.
2. What is the difference between WHERE and HAVING?
WHERE filters rows before grouping, while HAVING filters after grouping.
3. Can HAVING be used without GROUP BY?
It is not recommended and rarely used without GROUP BY.
4. When should I use HAVING?
Use HAVING when filtering aggregated or grouped data.
Internal Link
Want to explore more courses?
Click here for more free courses



