Oracle FAQ Your Portal to the Oracle Knowledge Grid
HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US
 

Home -> Community -> Usenet -> c.d.o.server -> Re: Subquery with null returns

Re: Subquery with null returns

From: <Kenneth>
Date: Thu, 27 Mar 2003 23:05:47 GMT
Message-ID: <3e83836b.8636258@news.inet.tele.dk>


On Thu, 27 Mar 2003 20:47:09 GMT, "David Wang" <ywang_at_adelphia.net> wrote:

>Hi, I have a subquery question, thanks for any response.
>"EMP" table has two columns "empno" and "mgr", I do this
>SELECT ENAME FROM EMP WHERE EMPNO NOT IN
>(SELECT MGR FROM EMP);
>I assumed this query will give me all employees who are not
>manager but it returns me "no rows selected" bacause one employee
>has null value in "MGR" column in subquery. Then I do,
>SELECT ENAME FROM EMP WHERE EMPNO IN
>(SELECT MGR FROM EMP);
>it gives me the names of all managers as it should.
>why with the same subquery one can retrives rows and one can't.
>I did this query on 8.1.7
>-DW-
>
>

Hi DW,

Because NULL values are discarded in joins, subqueries, correlated subqueries and comparison operators, "=","!=", ">" etc. That is the correct behaviour, because NULL is not comparable to anything, not even another NULL :

select 1 from dual where 1 != NULL;
and
select 1 from dual where NULL = NULL;

Returns no row.

1 is clearly not null, but the comparison 1 != NULL is impossible (That's why we have the IS (NOT) NULL operator). So no result.

Same with

  SELECT ENAME FROM EMP WHERE EMPNO NOT IN  (SELECT MGR FROM EMP); To check a NOT IN, Oracle must check against ALL the values in the subset, and one of these values is NULL. Oracle cannot make this comparison, so no rows.

On the other hand

  SELECT ENAME FROM EMP WHERE EMPNO IN
 (SELECT MGR FROM EMP); Oracle just needs to find ONE match in the subquery to return the row. It doesn't matter if there's a NULL in the subset , as soon Oracle has found just one match, it can ignore all other values, including the NULL.

Received on Thu Mar 27 2003 - 17:05:47 CST

Original text of this message

HOME | ASK QUESTION | ADD INFO | SEARCH | E-MAIL US