download

When should you filter with WHERE or HAVING?

SQL~6 minReviewed 2 Dec 2026Free · No sign-in

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_idstatusamount_cents
10paid3000
10paid2000
20void9000
20paid1200
30paid6000
30void4000
Show hints (2)
  1. "FILTER ROWS FIRST"

    Each sale has a status before you group anything.

  2. "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.

"SOLUTION · SQL"
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;
"OUTPUT"
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 →

Original OfferVibe question. SQLite SELECT · SQLite aggregate functions.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.