PostgreSQL HAVING

The HAVING clause is used in combination with the GROUP BY clause to limit your results based on aggregated data. For example what if you wanted to see the total salary per department you could use this SQ;

SELECT COUNT(*), SUM(salary) as total_salary, dept 
FROM employee GROUP BY dept;

+-------+--------------+-------------+
| count | totla_salary |    dept     |
+-------+--------------+-------------+
|     4 |      8697.30 | Finance     |
|     2 |      4666.10 | Engineering |
|     3 |      3388.55 | Sales       |
+-------+--------------+-------------+

This works well, but what if you only wanted to dee department with 3 or more employees? Using the HAVING clause will filter out the department with 2 or fewer employees.

SELECT COUNT(*), SUM(salary) as totla_salary, dept 
FROM employee 
GROUP BY dept HAVING count(*) > 2;

+-------+--------------+---------+
| count | totla_salary |  dept   |
+-------+--------------+---------+
|     4 |      8697.30 | Finance |
|     3 |      3388.55 | Sales   |
+-------+--------------+---------+