How do I filter grouped results in SQL with HAVING?
SELECT country, SUM(quantity * unit_price) AS revenue
FROM data
GROUP BY country
HAVING SUM(quantity * unit_price) > 200
ORDER BY revenue DESC;
Run this query in QueryLocal →
`WHERE` filters individual rows before grouping; `HAVING` filters the groups themselves after the aggregation has been computed. Here, only countries whose total revenue exceeds 200 make it into the result — you can't write this condition in a `WHERE` clause because `SUM()` doesn't exist yet at that stage of the query.
A table named data with columns: order_id (integer), customer (text), country (text), category (text), quantity (integer), unit_price (real), order_date (text, YYYY-MM-DD).