Lesson 4.4
SQL HAVING: Filtering Groups
HAVING is the filter that runs 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 descSchema · Garden ShopTable · order_items5 columns · 48 rows
Table · order_items
5 columns · 48 rowsOne row per line item within an order.
order_item_id intorder_id intproduct_id intquantity intunit_price decimal
Your task
For each product id, calculate units soldand gross sales. Keep only products with at least5 units sold, sorted by units sold.
SQL Workbench
⌘↵ to run·
Expected answer
- Columns: product_id, units_sold, gross_sales.
- Rows: 9 product groups.
- The first row should be product 6 with 12 units sold.
← Previous · 4.3 Grouping with GROUP BY
✓ Chapter 4 complete
You finished “Aggregations and Grouping.”
Nice work. Ready to start the next one?
Start Chapter 5: Joins →Begins with 5.1 Joining customers to orders