Combining WHERE and HAVING
You'll learn how to use WHERE and HAVING together in a single query to filter data at two different stages.
The Two-Stage Filter
Think of a query like a factory production line: WHERE filters the raw materials before they enter the machine, while HAVING inspects the finished products afterward. When you use both clauses together, you create a powerful two-stage filtering system.
Here's how the process works:
- WHERE filters first — It eliminates individual rows from the raw table before any grouping or aggregation happens
- GROUP BY groups — The remaining rows are organized into groups
- Aggregate functions calculate — Totals, averages, counts are computed for each group
- HAVING filters last — It removes entire groups based on their aggregated values
When to Use Both
Combining these clauses is essential when you need to:
- Exclude certain rows from consideration before summarizing
- Then filter the summary results themselves
For example: "Show me product categories where total sales exceed $10,000, but only count sales from the last year."
SELECT category, SUM(sale_amount) as total_sales
FROM sales
WHERE sale_date >= '2024-01-01'
GROUP BY category
HAVING SUM(sale_amount) > 10000;
The WHERE clause first removes all sales before 2024. Then we group by category, sum the amounts, and HAVING removes any category groups with totals under $10,000.
Efficiency Matters
Using WHERE is more efficient because it reduces the dataset early. Never use HAVING for something WHERE can do — always filter non-aggregated conditions with WHERE first.
Key Takeaway: WHERE and HAVING work as a team: WHERE filters individual rows before grouping, HAVING filters aggregated groups after — combining them gives you precise control over both raw data and summary results.