This topic describes the HAVING clause and how to use this clause.

Syntax

The following example shows the syntax of the optional HAVING clause:

HAVING condition

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

Description

The HAVING clause eliminates group rows that do not meet 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 that are 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 the 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)