SQL HAVING Clause

The HAVING clause was introduced in SQL to address the limitation of the WHERE keyword, which cannot be applied to aggregate functions.

SQL HAVING clause is used in combination with the GROUP BY clause to filter groups of data based on aggregate values. It acts as a filter on the groups of data returned by a SELECT statement with a GROUP BY clause. In other words, the HAVING clause specifies the conditions that must be met by the groups of data in order for them to be returned in the result set.

For example, let’s say you have a table that contains data about sales made by a salesperson. If you want to see the total sales for each salesperson and filter the results to only show the salespersons that have made more than $10,000 in sales, you would use the following query:

1SELECT salesperson, SUM(sales) as total_sales 2FROM sales_data 3GROUP BY salesperson 4HAVING SUM(sales) > 10000;

In this example, the SELECT statement retrieves the salesperson and the total sales, which is calculated using the SUM function. The GROUP BY clause groups the data by salesperson, and the HAVING clause filters the groups of data to only show those where the total sales is greater than $10,000.

It is important to note that the HAVING clause must come after the GROUP BY clause and before the ORDER BY clause in the SELECT statement.