Skip to content
/ Chapter 4 · Aggregations and Grouping
Lesson 4.4 · garden_shop
Lesson 4.4

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.

Pattern
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
Table · order_items

One row per line item within an order.

5 columns · 48 rows
order_item_id int order_id int product_id int quantity int unit_price decimal
Your task

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.