Difference Between WHERE and HAVING Clause in SQL

Learn via video course
FREE
View all courses
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
DBMS Course - Master the Fundamentals and Advanced Concepts
DBMS Course - Master the Fundamentals and Advanced Concepts
by Srikanth Varma
1000
5
Start Learning
Topics Covered

The WHERE clause in SQL is used to filter records and restrict the rows returned by a query based on specified conditions. It helps in extracting only those records that fulfill a particular criterion, making it essential for precise data retrieval and manipulation, serving as a fundamental difference when comparing where vs having in SQL.

Where VS Having Clause in SQL

When working with SQL, understanding the difference between the WHERE and HAVING clauses is pivotal for effective data manipulation and retrieval. Both clauses serve as filters but in distinct contexts and stages of query execution.

Consider a demo table named Employees to illustrate the use of WHERE and HAVING clauses. This table contains the following columns: EmployeeID, Name, Department, and Salary.

EmployeeIDNameDepartmentSalary
1John DoeMarketing50000
2Jane SmithSales60000
3Mike BrownIT70000
4Emily WhiteMarketing40000
5Alex GreenIT80000

What is a WHERE Clause?

The WHERE clause in SQL is a condition-based filter that is applied to rows returned by a SELECT statement. It specifies which rows to retrieve by including only those that meet a particular condition. This clause is fundamental for queries that require specific criteria to be met, enabling targeted data extraction from one or more tables based on the defined conditions.

Example: Let's use the above created table Employees and suppose we want to find employees in the IT department with a salary greater than 75000. We can construct a query with the WHERE clause as follows:

Output: After executing the query, we get the following result, which lists employees in the IT department earning more than 75000:

EmployeeIDNameDepartmentSalary
5Alex GreenIT80000

This output clearly demonstrates how the WHERE clause filters the dataset based on specified conditions, in this case, department and salary, to return a more focused set of results.

What is a HAVING Clause?

The HAVING clause in SQL is used in conjunction with the GROUP BY statement to filter groups or aggregates based on a specified condition. Unlike the WHERE clause, which filters rows, the HAVING clause filters groups created by GROUP BY. This makes it especially useful for working with aggregated data, such as counts, sums, averages, etc., where you want to apply conditions to groups rather than individual records.

Example: Let's use the above created table Employees and suppose we want to find departments whose average salary is above $60,000. To accomplish this, we would first group the records by department and then use the HAVING clause to filter these groups:

Output: Given the provided data, every department's average salary exceeds $40,000, so we expect to see all departments listed, along with their average salaries:

DepartmentAverageSalary
Marketing45000
Sales60000
IT75000

This output indicates that all departments—Marketing, Sales, and IT—have an average salary greater than $40,000, showcasing the HAVING clause's ability to filter groups after aggregation.

Difference between WHERE and HAVING Clause

Despite the fact that both HAVING and WHERE are used to filter the records and get only the required ones, there are some major differences between them that one should keep in mind to avoid mistakes while writing SQL queries. Some of the points that clearly elaborates on WHERE Vs HAVING in SQL are:

BasisWHERE clauseHAVING clause
Definitionused to filter individual rowsfilters group results
Basic functionalityrow operationcolumn operation
Aggregate functionsdoesn't work with aggregate functions in conditions. Example: WHERE COUNT(column_name) > value Xworks with aggregate functions in conditions.
Used withSELECT, UPDATE and DELETE commandsonly with SELECT statement
Data fetchingfetches only those records which fulfill the specified criteriafirst creates individual groups and then filters out the results
Conditionworks without GROUP BY clausecan't work without GROUP BY clause
GROUP BYused before GROUP BYused after GROUP BY
Type of Filterworks before grouping, hence as a PRE-FILTERworks after the groups are made, so it is referred to as POST-FILTER

When to Use WHERE and HAVING Clauses?

After learning WHERE Vs HAVING in SQL, we can note that the main difference between the two helps us decide which clause to use when. If the filtration of records is to be done before grouping, WHERE is used. And to filter the rows after grouping them, HAVING is used.

Assuming that filtration can be done without forming the groups, WHERE should be used first as it improves the performance of the query and gives the results quickly. After that, aggregate functions such as COUNT() and SUM() etc. can be applied on those filtered rows.

Can We Use Them Together?

The answer to this is "YES". HAVING and WHERE can be used to apply both the filters in a SELECT command only. Initially, the rows are filtered based on WHERE conditions. Then the rows are grouped by the column mentioned and aggregations are performed. Eventually, the HAVING clause is used to filter the obtained aggregated result.

Example:

USE OF WHERE AND HAVING CLAUSE TOGETHER

We are using the above table to demonstrate how we can use both the clauses together.

By this query, we are trying to get the total sales of cities Delhi and Mumbai only which have it greater than 10.

TOTAL SALES

Learn More

Conclusion

In the above article, we have studied that:

  • WHERE and HAVING clauses are both used for excluding some unwanted rows.
  • Multiple points that supports WHERE Vs HAVING in SQL.
  • The key difference between the two is WHERE clause doesn't incorporate aggregate functions while the HAVING clause does.
  • Different operators can be used to make required conditions while filtering.
  • When used together, WHERE performs first and keeps out the rows from the selection that don't fulfill the condition, and then HAVING does it functioning on the groups made.