13. HAVING: Filter Groups After Aggregates
13.3 How to Combine WHERE (Row Filter) and HAVING (Group Filter)
Why. Real questions often need both filters, such as deposits only, and only branches with enough of them.
What. Put the row condition in WHERE and the group condition in HAVING. WHERE runs first, so HAVING only sees totals made from the rows that WHERE kept.
How. Count deposits per branch with WHERE, then keep branches with at least 3 deposits using HAVING.
Steps
- Run the first example, which uses both WHERE and HAVING.
- Run the second example, which has HAVING only, and compare the counts.
- See that the counts change, because the second query counts every type of transaction.
- Decide which question your manager really asked before you choose.
Examples
Example 1 · dataset: northstar_bank
SELECT branch_id, COUNT(*) AS deposits
FROM transactions
WHERE txn_type = 'deposit'
GROUP BY branch_id
HAVING COUNT(*) >= 3
ORDER BY branch_id;Output
| branch_id | deposits |
|---|---|
| 2 | 3 |
| 3 | 3 |
| 4 | 4 |
Meaning. Only branches with 3 or more deposits are shown. Branches with fewer deposits were dropped by HAVING.
Example 2 · dataset: northstar_bank
SELECT branch_id, COUNT(*) AS all_transactions
FROM transactions
GROUP BY branch_id
HAVING COUNT(*) >= 3
ORDER BY branch_id;Output
| branch_id | all_transactions |
|---|---|
| 1 | 6 |
| 2 | 7 |
| 3 | 6 |
| 4 | 6 |
Meaning. Without WHERE, every branch passes, because cheques and withdrawals are counted too. This answers a different question.
Ravindra Bagale's Tip
In a grouped query, if a condition checks single rows and does not use SUM, COUNT, AVG, MIN or MAX, put it in WHERE. The query is clearer and does less work.
Ravindra Bagale's Tip – मराठी
Grouped query मध्ये condition एकेका row ला तपासत असेल आणि त्यात SUM, COUNT, AVG, MIN किंवा MAX नसेल, तर ती WHERE मध्ये ठेवा. Query स्पष्ट होते आणि कमी काम करते.
Ravindra Bagale's Tip – हिंदी
Condition में SUM, COUNT, AVG, MIN या MAX न हो, तो उसे WHERE में रखिए। Query साफ़ होती है और कम काम करती है।