PostgreSQL – HAVING clause
PostgreSQL has a HAVING clause that is used to eliminate groups of rows that do not meet specific criteria or conditions. Ii generally used in conjunction with the GROUP BY clause to filter group rows that do not satisfy a specified condition.
Now let’s analyze the above syntax:
- In the above syntax the aggregate_function represents functions like SUM(), COUNT() etc.
- The HAVING clause provides the condition for group rows created by the GROUP BY clause.
- The WHERE clause sets the condition for each row before the GROUP BY clause is applied.
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples. Example 1: Here we will query to selects the only customer who has been spending more than 200 USD using the HAVING clause in the “payment” table of our sample database.
SUM (amount) > 200;
Output: Example 2: Here we will query to select the stores that has more than 200 customers using the HAVING clause in the “customer” table of our sample database.
COUNT (customer_id) > 200;
Share your thoughts in the comments
Please Login to comment...