The HAVING keyword in SQL is used to filter rows in a result set after the GROUP BY operation has been applied. Unlike the WHERE clause, which filters rows before any grouping is performed, HAVING filters aggregated results.
Syntax:
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING aggregate_function(column2) condition;
Key Points:
- Usage: The
HAVINGclause is typically used with aggregate functions likeCOUNT(),SUM(),AVG(),MAX(), orMIN(). - Order: The
HAVINGclause is applied afterGROUP BYandWHERE. - Difference from WHERE:
WHEREfilters rows before grouping.HAVINGfilters groups after aggregation.
Example 1: Filter Groups by Aggregated Values
SELECT department, COUNT(employee_id) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(employee_id) > 10;
Explanation:
- This query groups employees by department.
- It counts the number of employees in each department.
- Only departments with more than 10 employees are included in the result.
Example 2: Combining WHERE and HAVING
SELECT product_id, SUM(sales) AS total_sales
FROM sales_data
WHERE region = 'North'
GROUP BY product_id
HAVING SUM(sales) > 10000;
Explanation:
- The
WHEREclause filters rows where the region is 'North'. - The
GROUP BYgroups the sales byproduct_id. - The
HAVINGclause filters groups where the total sales exceed 10,000.
Example 3: Using Multiple Conditions
SELECT category, AVG(price) AS average_price
FROM products
GROUP BY category
HAVING AVG(price) BETWEEN 20 AND 50;
Explanation:
- Groups products by category.
- Filters categories where the average price is between 20 and 50.
Summary:
- Use
HAVINGfor filtering aggregated data. - Use
WHEREfor filtering raw data before aggregation.
No comments:
Post a Comment