In SQL, the HAVING clause is used in combination with the GROUP BY clause to filter the result set based on conditions applied to aggregated data. While the WHERE clause filters individual rows before grouping, the HAVING clause filters groups after grouping and aggregation. The syntax for using HAVING is as follows:
sql
SELECT column1, column2, ..., aggregate_function(column)
FROM table
GROUP BY column1, column2, ...
HAVING condition;
In this syntax:
- `column1`, `column2`, etc. are the columns used in the GROUP BY clause.
- `aggregate_function(column)` is an aggregate function such as SUM, COUNT, AVG, MAX, MIN, etc., applied to a specific column or expression.
- `condition` is a filter condition applied to the aggregated data.
Here are a few examples to illustrate the usage of HAVING:
1. Find categories with total sales greater than 1000:
sql
SELECT category, SUM(sales) AS total_sales
FROM sales_table
GROUP BY category
HAVING SUM(sales) > 1000;
This query groups rows in the `sales_table` by the `category` column, calculates the total sales for each category using the SUM function, and then filters out groups where the total sales are greater than 1000 using the HAVING clause.
2. Find customers who have placed more than 5 orders:
sql
SELECT customer_id, COUNT(order_id) AS order_count
FROM orders_table
GROUP BY customer_id
HAVING COUNT(order_id) > 5;
This query groups rows in the `orders_table` by the `customer_id` column, counts the number of orders for each customer using the COUNT function, and then filters out groups where the order count is greater than 5 using the HAVING clause.
The HAVING clause allows you to apply filtering conditions to the result set based on aggregated data. It is particularly useful when you want to filter groups based on the result of aggregate functions. Remember that the HAVING clause operates on the grouped and aggregated data, while the WHERE clause operates on individual rows before grouping.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc