Sql Query To Use a ' SELECT ' statement with HAVING Clause


' HAVING ' clause is used to filter out the column with aggregate functions like count, sum, avg, min, max. It is done based on groups created by the GROUP BY Clause.

' WHERE ' clause can't be used to filter the column with an aggregate function. It is only used to filter normal columns.

Some of the examples are-

  1. Retrieve the number of employees in each department, whose department has employees greater than 5.
  2. Find the maximum salary of the employee in each department, whose department maximum salary is greater than 8000
  3. Find the minimum salary of the employee in each department, whose department minimum salary is greater than 8000.
  4. Calculate the average salary of the employee in each department. whose department average salary is less than 8000.
  5. Calculate the sum of the salary of the employee in each department. whose department salary sum is less than 20000.
Enter - Select * from table_name;
SQL Query
SELECT 'Retrieve the number of employees in each department,whose department has employee greater than 5'; SELECT COUNT(employee_id) FROM employees GROUP BY department_id HAVING COUNT(employee_id)>5; SELECT 'Find the maximum salary of the employee in each department, whose department maximum salary is greater than 8000'; SELECT MAX(salary) FROM employees GROUP BY department_id HAVING MAX(salary)>8000; SELECT 'Find the minimum salary of the employee in each department, whose department minimum salary is greater than 8000'; SELECT MIN(salary) FROM employees GROUP BY department_id HAVING MIN(salary)>8000; SELECT 'Calculate the average salary of the employee in each department. whose department average salary is less than 8000'; SELECT AVG(salary) FROM employees GROUP BY department_id HAVING AVG(salary)<8000; SELECT 'Calculate the sum of the salary of the employee in each department. whose department salary sum is less than 20000'; SELECT SUM(salary) FROM employees GROUP BY department_id HAVING SUM(salary)<20000;
Output