HAVING Clause in SQL
SQL HAVING clause tutorial with examples for beginners
The HAVING clause in SQL is used to filter records after they have been grouped using the GROUP BY clause. It is similar to the WHERE clause, but WHERE cannot be used with aggregate functions—HAVING can.
In this SQL tutorial, you will learn:
What the HAVING clause is
Difference between WHERE and HAVING
Syntax of HAVING
Examples with aggregate functions
GROUP BY + HAVING combinations
Real-world use cases
Best practices
The HAVING clause filters grouped records. It is used when you want to apply a condition on a summary result like:
Total salary
Count of employees
Average marks
Number of orders per customer
Since WHERE cannot be used with aggregate functions like SUM(), COUNT(), or AVG(), the HAVING clause is necessary.
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
| id | name | department | salary |
|---|---|---|---|
| 1 | Amit | IT | 50000 |
| 2 | Neha | HR | 45000 |
| 3 | Rahul | IT | 60000 |
| 4 | Sara | HR | 55000 |
| 5 | Karan | Finance | 70000 |
SELECT department, SUM(salary) AS total_salary
FROM employees
GROUP BY department
HAVING SUM(salary) > 100000;
| department | total_salary |
|---|---|
| IT | 110000 |
| HR | 100000+ |
SELECT department, COUNT(*) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(*) > 1;
SELECT department, AVG(salary) AS average_salary
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000
AND COUNT(*) >= 2;
| Feature | WHERE | HAVING |
|---|---|---|
| Filters rows before grouping | β | β |
| Filters rows after grouping | β | β |
| Works with aggregate functions | β | β |
| Used with SELECT and UPDATE | β | β |
SELECT department, SUM(salary) AS total_salary
FROM employees
WHERE salary > 40000
GROUP BY department
HAVING SUM(salary) > 100000;
SELECT customer_id, COUNT(*) AS total_orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) > 5;
SELECT product_id, SUM(quantity) AS total_sold
FROM sales
GROUP BY product_id
HAVING SUM(quantity) > 100;
SELECT city, AVG(order_amount) AS avg_amount
FROM orders
GROUP BY city
HAVING AVG(order_amount) > 1000;
β Use WHERE for row-level filtering before grouping
β Use HAVING for aggregated filtering after grouping
β Keep HAVING conditions simple for better performance
β Use proper indexes on GROUP BY columns
β Always pair GROUP BY with meaningful aggregate functions
In this SQL HAVING clause tutorial, you learned:
What HAVING does
How it filters grouped records
Difference between WHERE and HAVING
Examples using COUNT, SUM, AVG
Real-world scenarios
HAVING is essential for analytical queries and generating summary-based reports.