How to use SQL Having with group by clause

The Having clause

  • The having clause, is just like the where clause, that filters the results in aggregated data.
  • The Where clause cannot be used in the aggregated data, so SQL having clause is introduced to filter the results.
  • The having SQL clause is used with the Group by clause.
  • You can only use those column names in the having clause that are appeared in the Group by clause.
An example of having clause

SQL having syntax

The general syntax of using the having clause is:

select col_name, aggregate_function (col_name) from table_name

where col_name = value

group by emp_name

having aggragated_column=value;

To make it clearer, consider a scenario where a table is storing employee’s salaries paid every month.

Now you want to see how much salary has been paid till today to an employee?

Keep this scenario in mind and let us show you how Group by clause makes it quite easier and then only retrieving an individual’s sum of salary by using the having clause.

Examples of using having SQL clause

In this example, we will use the tbl_emp_salary_paid table that stores employees salaries.

A Having clause example with SUM function

This query will return total salary paid to the employee, Mike. To make it clearer, the first query in the graphic below (click the link) is without the having clause.

The having clause with sum query:


See having clause with sum example online

As you can see in the above graphic, two queries are shown. One with the simple group by clause to show all employees sum of salaries. The other query uses the having clause of SQL to retrieve only Mike’s salary.

A having clause example with Count function

This query will return the total number of salaries paid to Mike. To differentiate the results, the graphic is showing two views, one with the group by clause and the other with the having clause.

The SQL having with count query:


See having count example online

As you can see in the above graphic, two queries are shown. One with the simple group by clause to show the total number of salaries. The other query uses the having clause to retrieve only Mike’s total number of salaries.

Also see: SQL Group by

Was this article helpful?

Related Articles

Leave A Comment?