13. HAVING: Filter Groups After Aggregates
13.2 How to Keep Groups with HAVING SUM(amount) Above a Target
Why. A regional head wants to see only the months when a branch crossed a target, not every month.
What. HAVING SUM(amount) > number keeps only the groups whose total is above that number. Keep currencies apart: compare Indian branches with a rupee target and the London branch with a pound target.
How. Group the Mumbai and Pune rows by branch and month, then keep only the groups above 1,00,000 rupees.
Steps
- Run the first example and read which branch months crossed 1,00,000 rupees.
- Run the second example for London with a target of 5,000 pounds.
- Notice that each query looks at one currency only.
- Change the target number and run again to see more or fewer groups.
Examples
Example 1 · dataset: northstar_bank
SELECT branch_id,
strftime('%Y-%m', posted_at) AS month,
SUM(amount) AS total_inr
FROM transactions
WHERE branch_id IN (3, 4)
GROUP BY branch_id, month
HAVING SUM(amount) > 100000
ORDER BY branch_id, month;Output
| branch_id | month | total_inr |
|---|---|---|
| 3 | 2026-08 | 192000.0 |
| 3 | 2026-09 | 276000.0 |
| 3 | 2026-10 | 657000.0 |
| 4 | 2026-09 | 166000.0 |
Meaning. Only the branch months above 1,00,000 rupees remain. Pune in August and October stay out, because their totals are below that target.
Example 2 · dataset: northstar_bank
SELECT strftime('%Y-%m', posted_at) AS month,
SUM(amount) AS total_gbp
FROM transactions
WHERE branch_id = 1
GROUP BY month
HAVING SUM(amount) > 5000
ORDER BY month;Output
| month | total_gbp |
|---|---|
| 2026-10 | 7950.0 |
Meaning. For London, August and September stay below 5,000 pounds. Only October crosses the target, with 7,950 pounds.
Ravindra Bagale's Tip
SQLite lets you write HAVING total_inr > 100000 with the alias, but many other databases do not. Writing the full SUM(amount) works everywhere.
Ravindra Bagale's Tip – मराठी
SQLite मध्ये HAVING total_inr > 100000 असं alias वापरून लिहिता येतं, पण बऱ्याच इतर databases मध्ये नाही. पूर्ण SUM(amount) लिहिलं तर ते सगळीकडे चालतं.
Ravindra Bagale's Tip – हिंदी
SQLite में HAVING total_inr > 100000 जैसा alias लिख सकते हैं, पर कई दूसरे databases में नहीं। पूरा SUM(amount) लिखेंगे तो वह हर जगह चलेगा।