Syntax

The syntax of the optional HAVING clause is as follows:

HAVING condition

condition is the same as that specified for the WHERE clause.

Description

The HAVING clause eliminates group rows that do not satisfy the specified condition. The HAVING clause is different from the WHERE clause. The WHERE clause filters individual rows before the application of GROUP BY. The HAVING clause filters group rows created by GROUP BY. Each column referenced in a condition must explicitly reference a grouping column unless the column is referenced in an aggregate function.

Examples

To sum up the sal column for all employees, group the results by department number and show group totals that are less than 10,000.

SELECT deptno, SUM(sal) AS total
    FROM emp
    GROUP BY deptno
    HAVING SUM(sal) < 10000;

 deptno |  total
--------+---------
     10 | 8750.00
     30 | 9400.00
(2 rows)