The SQL HAVING clause is similar to SQL WHERE clause. The difference is that the SQL HAVING clause is used in aggregate functions but the SQL WHERE clause cannot be used in aggregate functions.

SQL HAVING clause Syntax

SELECT ColumnName1, ColumnName2, Aggregate_function (ColumnName)
FROM TableName
WHERE conditions
GROUP BY ColumnName1, ColumnName2
HAVING Aggregate_function (ColumnName) operator value

Note: The Aggregate_function could be SQL MAX, MIN, SUM, COUNT or AVG.

SQL HAVING Clause Example

Table: Employees

EmployeeId FirstName LastName Department Salary
203 Mazojys Fxoj Finance 78000
204 Jozzh Lnanyo Finance 45800
205 Syllauu Dfaafk Finance 57000
206 Gecrrcc Srlkrt Finance 62000
302 Jssme Bdnaa Development 75000
303 Dnnaao Errllov Development 55000
304 Tyoysww Osk Development 49000

Example 1
Select departments which has more than 3 employees:

SELECT Department, COUNT(EmployeeId)
FROM Employees
GROUP BY Department
HAVING COUNT(EmployeeId)>3

The result will look like:

Department COUNT(EmployeeId)
Finance 4

Example 2
Select departments whose minimum salary is more than $46,000:

SELECT Department, MIN(Salary)
FROM Employees
GROUP BY Department
HAVING MIN(Salary)>46000

The result will look like:

Department MIN(Salary)
Development 49000

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>