The Wayback Machine - https://web.archive.org/web/20240204104648/https://www.geeksforgeeks.org/postgresql-having-clause/
Open In App
Related Articles

PostgreSQL – HAVING clause

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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 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.

SELECT
    customer_id,
    SUM (amount)
FROM
    payment
GROUP BY
    customer_id
HAVING
    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.

SELECT
    store_id,
    COUNT (customer_id)
FROM
    customer
GROUP BY
    store_id
HAVING
    COUNT (customer_id) > 200;

Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Looking for a place to share your ideas, learn, and connect? Our Community portal is just the spot! Come join us and see what all the buzz is about!


Last Updated : 10 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads