SQL HAVING Clause
A HAVING clause in SQL specifies that an SQL SELECT statement should only return rows where aggregate values meet the specified conditions.
HAVING Clause Syntax
SELECT column_name(s)
FROM table_name
WHERE [condition]
GROUP BY column_name(s)
HAVING [condition]
ORDER BY column_name(s);
- HAVING Clause is used to filter the result combination with the GROUP BY clause to restrict thr groups of returned row to any those result whose the condition is TRUE.
- HAVING Clause must follow the GROUP BY Clause in a query and must also procede the ORDER BY Clause if used.
HAVING Syntax | Aggregate Function
SELECT column_name1, aggregate_function (aggregate_expression) column_alias
FROM table_name
WHERE [condition]
GROUP BY column_name1
HAVING column_alias > value;
Aggregate Function/Expression
- SUM, COUNT, MIN, MAX, or AVG functions are aggregate functions.
- The COLUMN or EXPRESSION that the aggregate function will be used on.
EXAMPLE: HAVING Clause
Employee Table
A sample of EMPLOYEE records table & the name of table Employee. The column(s) of the Employee table [ID, EMPLOYEE_NAME, EMPLOYEE_EMAIL, ADDRESS, CITY, and COUNTRY]:
ID |
EMPLOYEE_NAME |
EMPLOYEE_EMAIL |
ADDRESS |
CITY |
COUNTRY |
1 |
Mark J. |
mark@gmail.com |
House 53, Sq. |
London |
U.K. |
2 |
Lack Josh |
lackjosh@gmail.com |
2745 road mark |
Delhi |
India |
3 |
Kim Juhu |
kimjuhu@gmail.com |
Street 587327, 34 House |
Seoul |
South Korea |
4 |
Jack Jenifer |
jenifer@gmail.com |
464673 Mataderos |
Mexico D.F. |
Mexico |
5 |
McKinley |
mckinley@gmail.com |
54, Road Washington |
Washington |
U.S. |
6 |
Alena |
aln@gmail.com |
House No. 6563 |
Tokyo Japan |
Japan |
7 |
Mack Marina |
mmk@gmail.com |
43 Road, NH |
San Francisco |
U.S. |
8 |
Dipak Jha |
jha@gmail.com |
Mahanager, 26 Road |
Lucknow |
India |
Example HAVING Clause
SELECT COUNT (ID), ADDRESS
FROM Employee
GROUP BY ADDRESS
HAVING COUNT (ID) > 4;
Result Look Like
COUNT (ID) |
ADDRESS |
5 |
54, Road Washington |
6 |
House No. 6563 |
7 |
43 Road, NH |
8 |
Mahanager, 26 Road |