suppose there is a college database
name | state | enrollment
=============================
Stanford | CA | 15000
-----------------------------
Berkley | CA | 36000
-----------------------------
MIT | MA | 10000
-----------------------------
Cornell | NY | 21000
Without using max(), I can get the college with the maximum enrollment using exists operator and a subquery
select name from college c1 where not exists ( select * from college c2 where c2.enrollment > c1.enrollment);
This returns
Berkeley
(1 row)
as expected
Still,I can’t understand how the query worked. exists condition is met if the subquery returns at least one record.So,in the above ,the not exists would be met only if the subquery returns an empty set.Or so I thought..
To check this ,I tried to run the subquery
select c2.name from college c2,college c1 where c2.enrollment > c1.enrollment);
But this returns
name
----------
Stanford
Berkeley
Berkeley
Berkeley
Cornell
Cornell
(6 rows)
I am really confused here..can someone clarify how the first query worked and why I am wrong here?
The above query looks for records where it can find the enrollment value > current row of the outer query.
Assume that the query runs in a top-down sequence where it will
enrollment > Stanford enrollment . The subquery will return 2
records (Cornell & Berkley). So, it will not be a match.
NOT EXISTScondition will return true for Berkley.