Using the HAVING clause

In the previous section, we discussed about GROUP BY clause, however if you want to restrict the groups of returned rows, you can use HAVING clause. The HAVING clause is used to specify which individual group(s) is to be displayed, or in simple language we use the HAVING clause in order to filter the groups on the basis of an aggregate function condition.

Note: The WHERE clause cannot be used to return the desired groups. The WHERE clause is only used to restrict individual rows. When the GROUP BY clause is not used, the HAVING clause works like the WHERE clause.

The syntax for the PostgreSQL HAVING clause is as follows:

SELECT expression1, expression2, ... expression_n, 
aggregate_function (expression)
FROM tables
WHERE ...

Get PostgreSQL Development Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.