When should a SQL query use WHERE, GROUP BY and HAVING?
Answer
WHERE filters individual rows before grouping, GROUP BY forms groups for aggregate functions, and HAVING filters the resulting groups. For example, WHERE can restrict orders to one year, GROUP BY customer can calculate totals, and HAVING SUM(amount) greater than a threshold can retain only high-value customers. A strong test checks boundary values, nulls, duplicate join rows, grouping grain and an independently calculated control total.
Strong answer includes
- places row filtering before aggregation
- uses HAVING for aggregate conditions
- checks grouping grain and duplicate amplification
Practical example
The DATE 'YYYY-MM-DD' typed literal is SQL-standard syntax, but the browser runner uses SQLite, which does not support that typed DATE literal form.
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE order_date >= DATE '2025-01-01'
AND order_date < DATE '2026-01-01'
GROUP BY customer_id
HAVING SUM(amount) > 1000
ORDER BY total DESC;WHERE removes rows before aggregation, GROUP BY creates one group per customer, and HAVING keeps only aggregated groups whose total is above the threshold.
Expected result: Customers whose 2025 order total is greater than 1000.