T-SQL Tutorial

SQL HAVING


The HAVING clause in SQL Server is used to filter the results of a query based on aggregate functions. It is used in conjunction with the GROUP BY clause to filter groups of rows based on a specific condition. The HAVING clause is placed after the GROUP BY clause and before the ORDER BY clause in the query.


HAVING syntax

SELECT column_name(s), aggregate_function(column_name)
FROM my_table
WHERE condition {optional}
GROUP BY column_name(s)
HAVING (aggregate_function condition)


HAVING example

For example, the following query will group all rows in the "orders" table by customer, and then filter the groups to only include those where the sum of the "total" column is greater than 1000:

SELECT customer, SUM(total)
FROM orders
GROUP BY customer
HAVING SUM(total) > 1000;


It's important to note that the HAVING clause can only be used with SELECT statements, and cannot be used with UPDATE or DELETE statements. Also, It is not possible to reference any column that is not contained in the SELECT statement or the GROUP BY clause in the HAVING clause.

In summary, the HAVING clause is used in SQL Server to filter the results of a query based on aggregate functions, it can only be used in SELECT statement, and it's placed after GROUP BY clause before ORDER BY clause.