Filter Aggregate Groups: HAVING vs WHERE in MySQL
Overview & Learning Objectives
Filtering rows before grouping requires `WHERE`; filtering summarized groups after aggregation requires `HAVING`. Confusing `WHERE` and `HAVING` is one of the most frequent errors in data analytics. Because `WHERE` executes before `GROUP BY`, it cannot evaluate aggregate expressions like `SUM()` or `COUNT()`. Conversely, putting row-level filters in `HAVING` harms performance by forcing MySQL to group unnecessary rows before discarding them.
- Clearly differentiate row-level filtering (`WHERE`) from group-level filtering (`HAVING`).
- Filter aggregate groups based on volume thresholds (`HAVING COUNT(*) > 100`) and revenue ceilings.
- Optimize query execution by pushing pre-aggregation filters into `WHERE`.
Industry Standard
Standard: Analytics engineering teams at Uber enforce pushing all row filters to `WHERE` to minimize intermediate hash table size during grouping operations.
Real-World Example: ScoopCraft High-Volume Dark-Store Identification
ScoopCraft isolates dark stores that fulfilled more than 1,000 delivered orders and generated over ₹500,000 in monthly sales.
| Filtering Stage | Clause Used | Condition Evaluated | Performance Impact |
|---|---|---|---|
| Pre-Group Row Filter | WHERE | order_status = 'Delivered' | Eliminates cancelled orders before hash grouping |
| Post-Group Aggregate Filter | HAVING | COUNT(order_id) > 1000 | Filters out low-volume store summary rows |
| Post-Group Revenue Filter | HAVING | SUM(order_total) > 500000 | Retains only high-performing fulfillment hubs |
Syntax & Core SQL Implementation
-- Combining WHERE and HAVING in MySQL
SELECT
dark_store,
COUNT(order_id) AS total_orders,
ROUND(SUM(order_total), 2) AS gross_sales
FROM orders
WHERE order_status = 'Delivered' -- Step 1: Filter raw rows
AND order_date >= '2026-11-01' -- Step 1: Pre-aggregation filter
GROUP BY dark_store -- Step 2: Form groups
HAVING total_orders >= 1000 -- Step 3: Filter groups
AND gross_sales >= 500000.00
ORDER BY gross_sales DESC;
Parameters & Arguments Breakdown
WHERE clause: Filters individual atomic rows before any grouping occurs (cannot contain aggregate functions).HAVING clause: Filters aggregated group summary rows after GROUP BY completes (can evaluate SUM, COUNT, AVG).
Sample Walkthrough (Q&A)
Question: Why does "SELECT store_id, COUNT(*) FROM orders WHERE COUNT(*) > 5 GROUP BY store_id;" fail?
SQL Pattern: WHERE COUNT(*) > 5
Result: Error 1111 (HY000): Invalid use of group function
Explanation: WHERE executes before groups exist; it cannot compute or evaluate COUNT(*). The condition must be written as "HAVING COUNT(*) > 5".
Common Mistakes & Limitations
- Placing non-aggregate filters in `HAVING` (e.g. `HAVING status = "Delivered"`), which forces the database to group millions of unwanted records before filtering.
- Using `WHERE` to evaluate calculated aggregate totals like `SUM(sales) > 10000`.
Keyboard Shortcuts (MySQL Workbench)
| Action | Windows | Mac |
|---|---|---|
| Execute Query | Ctrl + Enter | Cmd + Enter |
Pro Tips & Modern Best Practices
- Rule of thumb: If your condition does not contain an aggregate function (`SUM`, `COUNT`, `AVG`, `MIN`, `MAX`), it belongs in the `WHERE` clause.
- In MySQL, you can reference `SELECT` aliases inside the `HAVING` clause directly (e.g. `HAVING gross_sales > 500000`).