I'm learning SQL using Oracle 10g. I need a query that returns the department with the most employees to use it in a update sentence. I already solved it, but I couldn't figure out why this query won't work:
select deptno
from (select deptno,
count(*) num
from emp
group by deptno)
where not num < any(select count(deptno)
from emp
group by deptno)
It puzzles me more since according to the documentation it should be equivalent and optimized into the following:
select deptno
from (select deptno,
count(*) num
from emp
group by deptno )
where not exists( select deptno,
count(*)
from emp
having count(*) > num
group by deptno)
That one works without errors. The following also work:
select deptno
from (select deptno,
count(*) num
from emp
group by deptno)
where num = (select max(alias)
from (select count(deptno) alias
from emp
group by deptno))
select deptno
from emp
group by deptno
having not count(deptno) < any( select count(deptno)
from emp
group by deptno)
Edit. Probably it'll help if I post the return values of the inner selects.
The first select returns:
Dept. Number Employees
30 6
20 5
10 3
The last one returns (3,5,6)
I checked them individually. It's also weird that if I put the values manually it works as expected and will return 30 as the department with most employees.
select deptno
from (select deptno,
count(*) num
from emp
group by deptno)
where not num < any(6,5,3)
I'm using Oracle 10g 10.2.0.1.0
Last edit, probably. Still don't know what's happening, but the behaviour is as if the last select is returning null somehow. So, even if I remove the ´not´, it still doesn't select anything.
If someone is interested I also found this useful: TSQL - SOME | ANY why are they same with different names? Read the first answer. It's probably better to avoid the use of any/some, all.