KnowledgeBoat Logo
|

Informatics Practices

Raj, a Database Administrator, needs to display the average pay of workers from those departments which have more than five employees. He is experiencing a problem while running the following query :

SELECT DEPT, AVG(SAL) FROM EMP WHERE COUNT(*) > 5 GROUP BY DEPT;

Which of the following is a correct query to perform the given task ?

  1. SELECT DEPT, AVG(SAL) FROM EMP WHERE COUNT(*) > 5 GROUP BY DEPT;
  2. SELECT DEPT, AVG(SAL) FROM EMP HAVING COUNT(*) > 5 GROUP BY DEPT;
  3. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT WHERE COUNT(*) > 5;
  4. SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT HAVING COUNT(*) > 5;

SQL Queries

2 Likes

Answer

SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT HAVING COUNT(*) > 5;

Reason — In the above query, the WHERE clause cannot be used with aggregate functions like COUNT(*) because it is meant to filter individual rows before the aggregation. On the other hand, the HAVING clause filters the groups created by the GROUP BY clause to include only those departments (DEPT) that have more than five employees.

Answered By

1 Like


Related Questions