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 ?
- SELECT DEPT, AVG(SAL) FROM EMP WHERE COUNT(*) > 5 GROUP BY DEPT;
- SELECT DEPT, AVG(SAL) FROM EMP HAVING COUNT(*) > 5 GROUP BY DEPT;
- SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT WHERE COUNT(*) > 5;
- SELECT DEPT, AVG(SAL) FROM EMP GROUP BY DEPT HAVING COUNT(*) > 5;
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.
Related Questions
What is the meaning of "HAVING" clause in SELECT query ?
- To filter out the summary groups
- To filter out the column groups
- To filter out the row and column values
- None of the mentioned
Where and Having clauses can be used interchangeably in SELECT queries ?
- True
- False
- Only in views
- With order by
Fill in the blanks:
To sort the rows of the result table, the _________ clause is specified.
Fill in the blanks:
Columns can be sorted in descending sequence by using the SQL keyword _________.