Wednesday, December 18, 2024

SQL HAVING Keyword

 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:

  1. Usage: The HAVING clause is typically used with aggregate functions like COUNT(), SUM(), AVG(), MAX(), or MIN().
  2. Order: The HAVING clause is applied after GROUP BY and WHERE.
  3. Difference from WHERE:
    • WHERE filters rows before grouping.
    • HAVING filters 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 WHERE clause filters rows where the region is 'North'.
  • The GROUP BY groups the sales by product_id.
  • The HAVING clause 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 HAVING for filtering aggregated data.
  • Use WHERE for filtering raw data before aggregation.

No comments:

Post a Comment