HAVING CLAUSE is haunting me
1)Friends i have a BIG confusion with HAVING CLAUSE.
In this expression part we use some normal columns(ex: HAVING deptno=20),Group function on some column(ex HAVING max(sal)>3000) or both combination of normal column and group function(ex: HAVING max(sal)>3000 and deptno=20).
Now, the columns which we are using in HAVING CLAUSE (in above examples sal,deptno) do they need to be present in both SELECT CLAUSE and GROUP BY CLAUSE or in either of the clause or they need not present in SELECT and GROUP BY clause.
I have tried a lot to get the answer for it but nobody has given a clear answer.
Friends please help me with this having clause GHOST its haunting me.
2)Query to retrieve the deptno of the employee who gets highest salary paid
SELECT deptno FROM emp HAVING sal=MAX(sal);
i am getting error.
Though there are many ways to get the answer for this query i want to know why this query dosent work as HAVING CLAUSE acts like WHERE CLAUSE in the absence of GROUP BY CLAUSE.
Thanks & regards
This query will tell you which department has the employee with the highest salary. But it won't tell you anything about who has that salary or what the highest salary.
If you want to use the having clause then you need to specify group by and use the having clause to compare aggregate values like count.
WHERE sal =
( SELECT MAX(sal)
FROM emp );
SELECT deptno, COUNT(*)
GROUP BY deptno
HAVING COUNT(*) > 1
ORDER BY 1;
this space intentionally left blank
Thanks Gandolf for replying i want some clarification from the answer
Originally Posted by gandolf989
Is it mandatory to use HAVING clause we need to specify GROUP BY clause.And is it mandatory to use only aggregate function in HAVING CLAUSE cant we use normal column ex: GROUP BY deptno HAVING deptno=10
To state it in simple terms: HAVING is the equivalent of the WHERE clause except it is applied after the query is executed and it filters the query results.
"The person who says it cannot be done should not interrupt the person doing it." --Chinese Proverb
Tags for this Thread
Click Here to Expand Forum to Full Width