SQL HAVING: Filtering Groups
HAVING filters groups: it applies after GROUP BY has created summary rows.
WHERE
filters individual rows before grouping.
HAVING
filters grouped summary rows after aggregates have been calculated.
Use
HAVING
when your condition depends on an aggregate like
sum(quantity)
or
count(*).
WHERE first, HAVING second
If a condition can be checked on each raw row, put it in
WHERE. If the condition needs an aggregate result, put it in
HAVING. That order keeps grouped reports predictable and easier to debug.
select group_column, sum(number_column) as total_value
from table_name
group by group_column
having sum(number_column) >= 5
order by total_value desc Schema · Garden Shop Table · order_items 5 columns · 48 rows
One row per line item within an order.
For each product id, calculate units sold and gross sales. Keep only products with at least 5 units sold, sorted by units sold (highest first), then by product id.
Run your query to inspect the result.
Expected answer
- Columns: product_id, units_sold, gross_sales.
- Rows: 9 product groups.
- The first row should be product 6 with 12 units sold.
Related
COUNT, SUM, AVG, MIN, MAX, GROUP BY, and HAVING.
COUNT, SUM, AVG, GROUP BY, and HAVING.
Practice aggregate reports, HAVING, and answer shape.
Avoid truncating fractional results.
Group or aggregate every selected column.
Searched and simple CASE patterns.