PostgreSQL HAVING Clause

In PostgreSQL, As Where clauses are not used with aggregate functions, so we use the HAVING clause to perform aggregate functions.The HAVING clause is used to restrict the results returned by Group BY Clause. It is used to give conditions on group functions.Having clause always executed at the end as a result of which it is also at the end in the syntax.


HAVING Syntax :

The syntax of the HAVING statement is −

SELECT  column_1, aggregate_function (column_2)
FROM  tbl_name
GROUP BY  column_1
HAVING  condition;



HAVING Example :

Consider the STUDENT table is having the following records

ID NAME AGE ADDRESS
1 Jugal 21 Indore
2 Kartik 19 Delhi
3 Ashish 18 Udaipur
4 Prateek 19 Jaipur
5 Pranjal 20 Mumbai
6 Vivek 24 Mumbai
7 Divesh 22 Udaipur
8 Ayush 21 Indore

TEST CASE 1 :- The following code is an example, which would fetch the all record from STUDENT table group by AGE and HAVING count of AGE is less than 2.

lfcdb-# SELECT AGE FROM STUDENT GROUP BY AGE HAVING count(AGE) < 2;


The result for the respective query is as follows −

AGE
18
20
22
24







Visit :


Discussion



* You must be logged in to add comment.