PostgreSQL HAVING Clause
PostgreSQL HAVING Clause
The HAVING clause in PostgreSQL is used to filter grouped results after the GROUP BY clause.
While WHERE filters rows, HAVING filters groups.
1️⃣ Why HAVING?
You cannot use aggregate functions (COUNT, SUM, AVG, etc.) in WHERE.
That’s where HAVING is needed.
2️⃣ Basic HAVING Syntax
3️⃣ Simple HAVING Example
✔ Shows only users with more than 2 orders.
4️⃣ HAVING with SUM
5️⃣ WHERE vs HAVING (Very Important)
Execution order:
FROMWHERE→ filters rowsGROUP BYHAVING→ filters groupsSELECTORDER BY
6️⃣ HAVING with Multiple Conditions
7️⃣ HAVING without GROUP BY
Allowed when using aggregate on entire table:
✔ Works on single group (whole table).
8️⃣ HAVING with JOIN
9️⃣ Common HAVING Conditions
| Condition | Example |
|---|---|
| Count | HAVING COUNT(*) > 5 |
| Sum | HAVING SUM(amount) > 1000 |
| Avg | HAVING AVG(amount) > 300 |
| Max | HAVING MAX(amount) > 500 |
🔟 Common Errors & Fixes
❌ Using aggregate in WHERE
✔ Move condition to HAVING
❌ Missing GROUP BY column
✔ Add non-aggregated columns to GROUP BY
1️⃣1️⃣ Best Practices
✔ Use WHERE before GROUP BY whenever possible
✔ Use HAVING only for aggregate conditions
✔ Keep HAVING logic simple
✔ Index columns used in WHERE and GROUP BY
Quick Summary
| WHERE | HAVING |
|---|---|
| Filters rows | Filters groups |
| Before GROUP BY | After GROUP BY |
| No aggregates | Aggregates allowed |
