What is the difference between WHERE clause and HAVING clause?
What is the difference between WHERE clause and HAVING clause?
The WHERE and HAVING clauses in SQL are both used to filter data, but they serve different purposes and are applied at different stages of query execution. Here are the key differences between them:
SELECT * FROM Employees WHERE Salary > 50000;
SELECT Department, AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY Department
HAVING AVG(Salary) > 50000;
Both WHERE and HAVING clauses can be used in the same query. In such cases, the WHERE clause filters rows before grouping, and the HAVING clause filters groups after aggregation.
Example:
SELECT Department, COUNT(*) AS EmployeeCount
FROM Employees
WHERE Age > 30
GROUP BY Department
HAVING COUNT(*) > 5;
This query first filters employees older than 30, then groups them by department, and finally filters those groups to include only departments with more than 5 employees.
| Feature | WHERE Clause | HAVING Clause |
|------------------------|------------------...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào