I'm reading the oracle documentation on the ANY and ALL operators. I pretty understand their uses except for one thing. It states:
ALL :
If a subquery returns zero rows, the condition evaluates to TRUE.
ANY :
If a subquery returns zero rows, the condition evaluates to FALSE.
It doesn't seem very logical to me. Why would ALL on an empty subquery would return TRUE but ANY returns FALSE?
I'm relatively new to SQL, so I assume it would have a use-case for this behavior which is really counter-intuitive to me.
ANY and ALL on an empty set should return the same value no?
The ANY and ALL operators are used with a WHERE or HAVING clause. The ANY operator returns true if any of the subquery values meet the condition. The ALL operator returns true if all of the subquery values meet the condition. Save this answer.
"All" means every one of the available choices. "Any" means some subset of the available choices. Depending on context, it may mean just one, or it could mean that more than one is allowed. "I'll take all of the candy in that box." If there are 30 pieces of candy in the box, then I want 30 pieces.
SQL WHERE with ANY, ALL ANY and ALL operate on subqueries that return multiple values. ANY returns true if any of the subquery values meet the condition. ALL returns true if all of the subquery values meet the condition.
The ANY and ALL operators allow you to perform a comparison between a single column value and a range of other values.
Consider the example of the EMP
table in that link.
Specifically this query -
SELECT e1.empno, e1.sal
FROM emp e1
WHERE e1.sal > ANY (SELECT e2.sal
FROM emp e2
WHERE e2.deptno = 20);
In case of ANY, the question you are asking is "Is my salary greater than anyone in department 20 (at least 1 person)". This means you are hoping at least one person has a salary less than you. When there are no rows, this returns FALSE
because there is nobody whose salary is less than you, you were hoping for at least one.
In case of ALL, the obvious question you would be asking is "Is my salary greater than everyone?". Rephrasing that as "Is there nobody that has salary greater than me?" When there are no rows returned, your answer is TRUE
, because "there is indeed nobody whose salary is greater than me.
Because ANY
is to be interpreted as EXIST
(if there is any, it means they exist). Therefore, it return false if no rows are found.
All
does not certify that any values exist, it just certifies that it represents all possible values. Therefore, it return true even if no rows are found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With