postgresql
  1. postgresql-having

HAVING Clause - (PostgreSQL)

The PostgreSQL HAVING clause is used with the GROUP BY clause to specify a condition for filtering group results. It is used to filter out the groups that do not meet the specified condition. In this tutorial, we'll discuss the syntax, example, output, explanation, use, important points, and summary of the HAVING clause in PostgreSQL.

Syntax

SELECT column1, column2, aggregate_function(column3)
FROM table_name
WHERE [condition]
GROUP BY column1, column2
HAVING [condition];
  • column1, column2, column3: The columns to select and group by.
  • aggregate_function: The aggregate function to apply to column3.
  • table_name: The name of the table to select from.
  • condition: The condition to filter the result set.

Example

Let's take a look at an example of using the HAVING clause.

SELECT category, COUNT(*) as count
FROM products
GROUP BY category
HAVING COUNT(*) > 5;

The output of this query would be all the categories and their count where the count of products in each category is greater than 5.

category  | count
----------+-------
electronics      | 8
clothing    | 7

Explanation

In the above example, we used the HAVING clause to filter out the results. The GROUP BY clause groups the result set by category, and the COUNT(*) function counts the number of products in each category. The HAVING clause filters out the groups where the number of products is less than or equal to 5.

Use

The HAVING clause is used to filter out groups that do not meet the specified condition. It is useful when you want to see only the results that meet a certain criteria.

Important Points

  • The HAVING clause is always used with the GROUP BY clause.
  • The HAVING clause is applied after the GROUP BY clause, so it only filters out groups after the results have been grouped by the GROUP BY clause.
  • The conditions specified in the HAVING clause can use aggregate functions.

Summary

In this tutorial, we discussed the HAVING clause in PostgreSQL. We covered the syntax, example, output, explanation, use, and important points of the HAVING clause. With this knowledge, you can now use the HAVING clause to filter out groups that do not meet the specified condition when using the GROUP BY clause in your PostgreSQL queries.

Published on: