13. HAVING: Filter Groups After Aggregates
13.1 WHERE vs HAVING in One Picture
Why. WHERE and HAVING both filter, so beginners mix them up. Knowing which one runs when keeps your totals correct.
What. SQLite reads a query in this order: FROM, then WHERE on single rows, then GROUP BY, then HAVING on whole groups. WHERE cannot use SUM or COUNT, because the groups do not exist yet. HAVING can, because it runs after the totals are made.
How. Use WHERE to keep only deposits, and HAVING to keep only accounts with at least 4 transactions.
Steps
- Run the first example: WHERE removes rows before grouping.
- Run the second example: HAVING removes groups after counting.
- Read the picture: rows, then WHERE, then groups, then HAVING, then the result.
- Remember: in a grouped query like this one, a condition on a group's SUM or COUNT goes in HAVING, and a condition on single rows goes in WHERE.
Examples
Example 1 · dataset: northstar_bank
SELECT branch_id, COUNT(*) AS deposits
FROM transactions
WHERE txn_type = 'deposit'
GROUP BY branch_id
ORDER BY branch_id;Output
| branch_id | deposits |
|---|---|
| 1 | 2 |
| 2 | 3 |
| 3 | 3 |
| 4 | 4 |
Meaning. WHERE kept only deposit rows, and then GROUP BY counted them for each branch.
Example 2 · dataset: northstar_bank
SELECT account_id, COUNT(*) AS transactions
FROM transactions
GROUP BY account_id
HAVING COUNT(*) >= 4
ORDER BY account_id;Output
| account_id | transactions |
|---|---|
| 103 | 4 |
Meaning. Only account 103 has 4 or more transactions, so HAVING kept just that one group. The other seven accounts were counted first and then dropped.
- All rows from FROM
- WHERE keeps matching rows
- GROUP BY makes groups
- HAVING keeps matching groups
- SELECT shows the result
Ravindra Bagale's Tip
If you write WHERE SUM(amount) > 1000, SQLite gives an error about misuse of an aggregate. That error means: move this condition to HAVING.
Ravindra Bagale's Tip – मराठी
WHERE SUM(amount) > 1000 लिहिलं तर SQLite aggregate च्या चुकीच्या वापराचा error देतं. त्या error चा अर्थ: ही condition HAVING मध्ये हलवा.
Ravindra Bagale's Tip – हिंदी
WHERE SUM(amount) > 1000 लिखेंगे तो SQLite aggregate के गलत इस्तेमाल का error देगा। उस error का मतलब है: यह condition HAVING में ले जाइए।