Free Web Development Online Tutorials, Learn to Code
Having clause, group by, distinct in SQL Tutorial, MS SQL Tutorial Online

SQL Having clause, group by Example

When to 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.

Having clause, Group by Example

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

SELECT COUNT(Email),Email FROM tbStudent
GROUP BY Email
HAVING COUNT(Email) > 1

HAVING Clause with Group By, Order By

Now you can also add order by clause in above query.

SELECT COUNT(Email),Email, Name FROM tbStudent
GROUP BY Email
HAVING COUNT(Email) > 1
Order By Email
Comment
Name
Email
Website
Subscribe