How does 'in' clause works in oracle

前端 未结 5 1584
遇见更好的自我
遇见更好的自我 2020-12-11 04:46
select \'true\' from dual where 1 not in (null,1);

when we execute this which will result nothing

what my question is:

is the above

相关标签:
5条回答
  • 2020-12-11 04:51

    The issue of your script in comparing with NULL value. You should use

    column is null and column = 1
    

    Actually NULL is an undefined value. Any comparation with NULL gives neither True nor False but NULL. Even NULL = NULL

    That's why your 1 not in (null,1) doesn't work.

    0 讨论(0)
  • 2020-12-11 04:59

    The IN statement is a collection of OR statements, while NOT IN is a collection of AND statements - but it is also not equal to.

    So the NOT IN is equivalent to:

    1 <> NULL
    AND 1 <> 1
    AND ...
    

    While the IN would be equivalent to:

    1 = NULL
    OR 1 = 1
    OR ...
    

    Note that having NULL in the collection will not work, due to the quirky nature of NULL.

    0 讨论(0)
  • 2020-12-11 05:09

    Yes they are.

    select something from table where column not in (1,2,3);
    

    is equivalent to

    select something from table where column != 1 and column != 2 and column != 3;
    
    0 讨论(0)
  • 2020-12-11 05:09

    Yes. It is correct. Also NULL values should be compared with IS NULL

    0 讨论(0)
  • 2020-12-11 05:17

    Correct (but note that IN is an operator, not a clause and it works like this in SQL in general, not only for Oracle).

    where 1 not in (null,1)
    

    is equivalent to:

    where 1 != null and 1 != 1
    

    which should really be written as:

    WHERE 1 NOT IN (NULL, 1)
    

    and

    WHERE 1 <> NULL AND 1 <> 1
    

    which is the same as:

    WHERE (1 <> NULL) AND (1 <> 1)
    

    which evaluates to:

    WHERE UNKNOWN AND FALSE
    

    and further as:

    WHERE FALSE
    

    So, it correctly returns no rows.


    Notice that if you had WHERE 1 NOT IN (NULL, 2), it would evaluate to WHERE UNKNOWN (left as an exercise) and no rows would be returned either.

    0 讨论(0)
提交回复
热议问题