SQL HAVING Clause
In its most common usage, SQL HAVING clause is a SQL WHERE clause for groups. Just as SQL WHERE clause limits rows, SQL HAVING clause limits groups. In most programming contexts, you will use SQL HAVING clause after SQL GROUP BY clause to limits groups by searched conditions.
Here we have two tables
Departments
department_id name
------------- --------------------
1 Software Engineering
2 Sale
3 Marketing
4 HR
employee_id name department_id job_id salary
----------- -------- ------------- ------ -------
1 jack 1 1 3000.00
2 mary 2 2 2500.00
3 newcomer (NULL) 0 2000.00
4 anna 1 1 2800.00
5 Tom 2 2 2700.00
6 foo 3 3 4700.00
Here we can find out which department has equal or more than 2 employees:
SELECT D.name as department_name,
count(employee_id) AS employee_count
FROM employees AS E
INNER JOIN departments AS D
ON D.department_id = E.department_id
GROUP BY department_name
HAVING employee_count >= 2
department_name employee_count
-------------------- --------------
Sale 2
Software Engineering 2
Related Tutorials