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. 

POINTS:

  • 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]
FROM [table_name]
[WHERE  CONDITIONS]
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
WHERE ID=GENREID
GROUP BY GENRE HAVING COUNT(TITLE) >1;

GENRECOUNT
CLASSIC2
ROMANCE2

Related Posts