What is the difference between WHERE clause and HAVING clause?
What is the difference between WHERE clause and HAVING clause?
WHERE filters rows before grouping. HAVING filters groups after aggregation.
SELECT department, COUNT(*) AS headcount, AVG(salary) AS avg_salary
FROM employees
WHERE status = 'active' -- row filter, runs first
GROUP BY department
HAVING COUNT(*) >= 5 -- group filter, runs after the aggregate
AND AVG(salary) > 60000
ORDER BY avg_salary DESC;
FROM -> JOIN -> WHERE -> GROUP BY -> HAVING -> SELECT -> DISTINCT -> ORDER BY -> LIMIT.
This order explains the rules:
WHERE cannot use aggregates (WHERE COUNT(*) > 5 is an error) because groups do not exist yet.Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.