🗄️ SQL Q1 / 104

What is the difference between WHERE and HAVING clause?

AI-Powered Answer ✓ Answered

In SQL, both the WHERE and HAVING clauses are used to filter data, but they operate at different stages of query processing and on different types of data. Understanding their distinct roles is crucial for writing efficient and correct SQL queries.

The WHERE Clause

The WHERE clause is used to filter individual rows based on specified conditions *before* any grouping occurs. It operates on rows retrieved from the FROM clause and can filter data based on columns that are not aggregated. It cannot directly contain aggregate functions.

sql
SELECT product_name, price
FROM products
WHERE price > 50;

The HAVING Clause

The HAVING clause is used to filter *groups* of rows based on specified conditions *after* the GROUP BY clause has been applied. It typically operates on the results of aggregate functions (like SUM, COUNT, AVG, MAX, MIN) and filters the groups that meet the criteria. If no GROUP BY clause is present, HAVING acts on the entire result set as a single group.

sql
SELECT department, COUNT(employee_id) AS total_employees
FROM employees
GROUP BY department
HAVING COUNT(employee_id) > 5;

Key Differences and Comparison

FeatureWHERE ClauseHAVING Clause
PurposeFilters individual rowsFilters groups of rows
Execution StageBefore GROUP BYAfter GROUP BY
ApplicabilityWorks on individual rows/columnsWorks on aggregate functions/groups
Aggregate FunctionsCannot use aggregate functions directlyCan and often does use aggregate functions
Data FilteringFilters data before aggregationFilters data after aggregation
Columns UsedNon-aggregated columnsAggregated columns (from GROUP BY) or aggregate functions

Summary

In essence, use WHERE to filter individual records before they are grouped, and use HAVING to filter the results of groups after aggregation. Combining both clauses allows for precise control over data filtering at different stages of a SQL query's execution.