SQL HAVING Clause

In SQL, the HAVING clause is used in conjunction with the GROUP BY clause to filter the results of a query based on aggregate values.

It is used to filter the groups based on a certain condition, much like the WHERE clause filters the individual rows.

Syntax

The basic syntax of the HAVING clause is as follows:

SELECT column1, aggregate_function(column2)
FROM table1
GROUP BY column1
HAVING aggregate_condition;

Here, column1 and aggregate_function(column2) are the columns that you want to select and the aggregate function that you want to apply to column2, respectively.

The GROUP BY clause is used to group the rows based on the value of column1, and the HAVING clause is used to filter the groups based on the condition specified in aggregate_condition.

Examples

Using HAVING to filter groups based on aggregate values

Consider a table called “orders” that contains information about customer orders.

The following query groups the orders by customer and calculates the total value of each customer’s orders.

It then filters the results to only show customers whose total order value is greater than 1000:

SELECT customer, SUM(value) as total_value
FROM orders
GROUP BY customer
HAVING SUM(value) > 1000;

Using HAVING to filter groups based on multiple aggregate values

Consider a table called “employees” that contains information about employee details.

The following query groups the employees by department and calculates the average salary and the number of employees in each department.

It then filters the results to only show departments where the average salary is greater than 50000 and the number of employees is greater than 10:

SELECT department, AVG(salary) as avg_salary, COUNT(*) as num_employees
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000 AND COUNT(*) > 10;

Using HAVING with subquery

Consider a table called “sales” that contains information about sales details.

The following query groups the sales by product and calculates the total sales of each product.

It then filters the results to only show products whose total sales is greater than the average total sales of all the products:

SELECT product, SUM(sales) as total_sales
FROM sales
GROUP BY product
HAVING SUM(sales) > (SELECT AVG(SUM(sales)) FROM sales GROUP BY product);

Conclusion

The HAVING clause is a powerful tool in SQL that allows you to filter the results of a query based on aggregate values.

It can be used in conjunction with the GROUP BY clause to filter groups based on a certain condition, much like the WHERE clause filters individual rows.

The examples above illustrate some common use cases of the HAVING clause, but it can also be used in other ways to suit the specific needs of your query.

Related Posts: