When should you filter with WHERE or HAVING?
Question
Report each store with at least 5000 cents of paid sales. Include the store ID and paid total. Exclude void sales before adding amounts. Sort by store ID.
sales
| store_id | status | amount_cents |
|---|---|---|
| 10 | paid | 3000 |
| 10 | paid | 2000 |
| 20 | void | 9000 |
| 20 | paid | 1200 |
| 30 | paid | 6000 |
| 30 | void | 4000 |
Show hints (2)
- "FILTER ROWS FIRST"
Each sale has a status before you group anything.
- "FILTER TOTALS LATER"
The store's total only exists after its paid rows are grouped.
Show checked explanation
Filter individual sales with WHERE status = 'paid'. Group by store and filter totals with HAVING SUM(amount_cents) >= 5000.
SELECT store_id, SUM(amount_cents) AS paid_cents FROM sales WHERE status = 'paid' GROUP BY store_id HAVING SUM(amount_cents) >= 5000 ORDER BY store_id;
store_id | paid_cents 10 | 5000 30 | 6000
Ran the query on SQLite 3.49 with the sample rows and edge cases.
Walkthrough
The paid rows for store 10 add up to 5000, exactly on the threshold. Only 1200 cents remain for store 20 after filtering. Store 30 has 6000 cents in the result because its void row was removed before the sum.
Common mistakes
- Putting the aggregate in
WHERE, before the store total exists. - Summing all statuses and checking a single status after grouping.
- Using
>and dropping the store that meets the threshold exactly.
Follow-up questions
- "How do you report stores with zero paid sales too?" Start with a stores table and left join paid sales. Use
COALESCE(SUM(amount_cents), 0)and remove the minimum total filter. - "How do you filter on sale date as well?" Add the date range to
WHERE, so all totals use only sales from the requested period.
What a strong answer covers
Apply one predicate to each input row and the other to the aggregate. Account for the inclusive threshold.
Open in interactive practice deck →