What is the difference between the WHERE clause and the HAVING clause in SQL?
What is the difference between the WHERE clause and the HAVING clause in SQL?
239
30-Jun-2023
Updated on 02-Jul-2023
Aryan Kumar
02-Jul-2023The WHERE and HAVING clauses in SQL are both used to filter the results of a SELECT statement. However, they work in different ways.
The WHERE clause is used to filter the rows of data before any grouping is done. It is used to filter individual rows, based on certain conditions. For example, the following WHERE clause will only return rows where the
customer_idis equal to 100:SQL
The HAVING clause is used to filter the groups of data after grouping has been done. It is used to filter groups of rows, based on conditions involving aggregate functions. For example, the following HAVING clause will only return groups where the average order amount is greater than $100:
SQL
In other words, the WHERE clause filters the rows before they are grouped, and the HAVING clause filters the groups after they are grouped.
Here is a table that summarizes the key differences between the WHERE and HAVING clauses: