PostgreSQL Having
What Is HAVING in PostgreSQL?
When you group records using GROUP BY, you might want to filter the grouped results. That’s where HAVING comes in—it lets you apply conditions after the grouping is done.
Think of HAVING as the post-grouping filter, unlike WHERE, which filters before rows are grouped.
Why Use HAVING?
While WHERE works on individual entries, HAVING works on aggregated results like totals, counts, or averages. It helps you narrow down grouped outcomes based on your specific needs.
Example: Show Customers With 5+ Orders
Let’s say we want to find users who’ve placed at least five purchases:
SELECT customer_id, COUNT(*) AS total_orders FROM orders GROUP BY customer_id HAVING COUNT(*) >= 5;
This gives us only those customer IDs whose total orders are five or more.
Another Case: Filter by Total Value
Imagine you're calculating how much revenue each store location has made:
SELECT store, SUM(amount) AS total_revenue FROM transactions GROUP BY store HAVING SUM(amount) > 10000;
This returns stores with total revenue exceeding ₹10,000.
Comparison: WHERE vs. HAVING
| Clause | Works On | Used With Aggregates? |
|---|---|---|
| WHERE | Raw table rows | ❌ No |
| HAVING | Grouped outcomes | ✅ Yes |
Mixing WHERE and HAVING
You can use both WHERE and HAVING in one query. For example:
SELECT product, COUNT(*) AS sold FROM sales WHERE region = 'West' GROUP BY product HAVING COUNT(*) > 50;
Here:
WHERE filters only the 'West' region entries.
HAVING ensures only products with more than 50 sales are returned.
Prefer Learning by Watching?
Watch these YouTube tutorials to understand POSTGRESQL Tutorial visually:
What You'll Learn:
- 📌 GROUP BY and HAVING Clause in SQL
- 📌 Group By And Having Clause In SQL | Group By Clause In SQL | SQL Tutorial For Beginners |Simplilearn