WHERE & HAVING clauses are the building blocks of the SQL query, this page will explain difference between WHERE & HAVING clauses.

SQL: WHERE Vs HAVING

WHERE & HAVING clauses are the building blocks of the SQL query, this page will explain difference between WHERE & HAVING clauses. Query statement is possible without any of WHERE & HAVING clauses.


Comparison between WHERE & HAVING clauses based on usage


WHERE Clause

HAVING Clause

Usage on Filtering Data

WHERE clause can be used to Filter Data.

HAVING clause can also be used to Filter Data.

Usage on Aggregated Columns

WHERE clause cannot be used on aggregated columns to filter data.

HAVING clause must be used to filter data on aggregated columns

Usage when GROUP BY Clause is present

WHERE clause can be used on all the columns which are present in GROUP BY clause.

HAVING clause can also be used on all the columns which are present in GROUP BY clause.

Usage when GROUP BY Clause is not present

WHERE clause does not have any such limitation.

HAVING clause cannot be used on non-aggregated columns if there is no GROUP BY clause in the query.

Usage when Filtering Column is not present in SELECT

Non aggregated filtering column will work with WHERE clause even that column may not be part of SELECT Statement.

Non aggregated filtering column can not be used in HAVING clause if those are not present in SELECT.

Simultaneous Usage

WHERE clause can be used in the same query along with HAVING.

HAVING clause can also be used in the same query along with WHERE.

Note: Tables and data used in the below examples can be found here .


Demonstration 1: Usage of HAVING & WHERE clause.




Demonstration 2: Inproper usage of HAVING & WHERE clause.