Join Class

Sql Having clause with group by

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.

Use having clause in SQL Statement?

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.

SQL Having clause with Group by Example

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

having clause, group by

Having clause with group by

Here is simple example of using having clause with group by in sql query.

SELECT COUNT(Email),Email FROM tbStudent
having clause with group by, order by

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
Order By Email
SQL having clause vs where clause

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

Hire SQL Developer
Having Clause in SQL Server
SQL Training: For any group or corporate training, please contact us at webtrainingroom(at)gmail.
SQL job Interview Questions Answers
Course in Demand
SQL database development tutorials for learning sql query, data manipulation language, working with MS SQL Server.
MS SQL Examples | Join MS SQL Course