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.
Syntax: SELECT column_1, aggregate_function (column_2) FROM tbl_name GROUP BY column_1 HAVING 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 fro 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.
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.
SELECT customer_id, SUM (amount) FROM payment GROUP BY customer_id HAVING SUM (amount) > 200;
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.
SELECT store_id, COUNT (customer_id) FROM customer GROUP BY store_id HAVING COUNT (customer_id) > 200;