Basic Queries & FilteringBeginner
1Question 1 of 1
sqlHow does WHERE filtering differ from HAVING filtering in SQL aggregate queries?
Explanation & Concept
The WHERE clause filters individual rows before any groupings or aggregate calculations take place. In contrast, the HAVING clause filters groups after the GROUP BY clause and aggregate calculations (like COUNT, SUM, AVG) have been evaluated.
You cannot use aggregate functions directly in a WHERE clause (e.g., WHERE SUM(amount) > 100 is invalid), because individual rows do not have an aggregated sum until grouped.
Code Example
sql
SELECT
department_id,
COUNT(employee_id) AS total_staff,
AVG(salary) AS avg_department_salary
FROM employees
WHERE employment_status = 'Active' -- Filters rows before grouping
GROUP BY department_id
HAVING COUNT(employee_id) >= 5 -- Filters groups after aggregation
AND AVG(salary) > 75000;How It Works & Key Takeaways
Here, inactive employees are removed before grouping by `department_id`. The engine then computes total employees and average salary per department, and HAVING filters out departments with fewer than 5 members or an average salary of $75,000 or below.
Mock Test · 1 Questions · Optional
Ready for Aggregate Functions & GROUP BY?
Take a quick test to evaluate yourself, or move straight to the next module.
Beginner1 questions