Sql Having clause is used to filter values after grouping in sql query.
In this tutorial you will learn how to use sql having clause with group by clause.
When you need having clause in SQL statement? Just assume you have a large number of records in a table, and there are many duplicate email ids (or any other column value), you want to find out which are those records, in such scenario you can use having clause.
having clause in sql was added because the WHERE keyword could not be used with aggregate functions.
Here is an example of how to use SQL Having clause with Group by and Order By statement
SELECT columnName(s) FROM table_name WHERE condition GROUP BY columnName(s) HAVING condition ORDER BY columnName(s);
In below screenshot you can see how having clause is been used to find the duplicate email ids
Here is simple example of using having clause with group by in sql query.
SELECT COUNT(Email),Email FROM tbStudent GROUP BY Email HAVING COUNT(Email) > 1
Now you can also add order by clause in above query, see how to use "having count" with group by query.
SELECT COUNT(Email),Email, Name FROM tbStudent GROUP BY Email HAVING COUNT(Email) > 1 Order By Email
Now you may think how sql having clause is different than sql where clause, though there is some similarity in nature like filtering records, but there are some difference also, let's understand with example.
Sql WHERE clause is used for filtering records before any groupings clause executed
When SQL having clause filter records after grouping is done.
You may be interested in following posts