SQL HAVING Clause – Having clause is used to retrieve records on the basis of some condition. It is same like SQL WHERE Clause except that the having clause can be used with Aggregate functions like SUM, AVG and Count etc.
- HAVING condition can restrict the data that results using group by clause.
- Aggregate function cannot be used in WHERE condition where as HAVING can be used.
- WHERE condition filters the data before using Group By Clause. Whereas HAVING filters the data after Group By clause.
- WHERE condition can be used for both Grouped and non-Grouped queries
- It is not mandatory to use Group By clause for an SQL Select statement with HAVING condition
- HAVING allows to perform conditional operations on aggregate values.
SQL HAVING Clause Syntax
SELECT [column_1], [column_2]……………….,aggregate_function[Column_n]
GROUP BY [column_1],[column_2]…………..[Column_n][ HAVING [CONDITIONS]];
SQL Having Query Example
Count more than 1 title with same genre.
SELECT GENRE ,COUNT(TITLE) AS COUNT FROM GENRES,BOOKS
GROUP BY GENRE HAVING COUNT(TITLE) >1;