The NOT IN with NULL values dilemma in ORACLE SQL

前提是你 提交于 2021-01-29 13:23:19

问题


When I used this code

WHEN col1 NOT IN (SELECT col2 FROM table_name) THEN 'something'

it didn't give the expected results knowing that col2 contains a NULL value, Why did this happened ? Does using IN with NULL values messes with data stored in memory or what?


回答1:


This is not an issue with Oracle. This is how SQL is defined.

When the subquery returns a NULL value with NOT IN, then no rows match at all. For this reason, I strongly recommend always using NOT EXISTS instead:

WHEN NOT EXISTS (SELECT 1 FROM bst WHERE x.n = bst.p)
     THEN 'Leaf'

As a corollary, I usually use EXISTS instead of IN, even though it does not have this problem.

Why does this occur? NULL means that the value is unknown, not that the value is "missing" or something else.

So, if all the elements have values, this is easy to calculate:

1 NOT IN (1, 2)  --> false
3 NOT IN (1, 2)  --> true

However:

1 NOT IN (1, 2, NULL)  --> false 
3 NOT IN (1, 2, NULL)  --> NULL, because NULL could be equal to "3"

Basically, if any value is NULL, then NOT IN returns either "false" or NULL. Both "false" and NULL are treated the same in WHEN and WHERE.



来源:https://stackoverflow.com/questions/60788886/the-not-in-with-null-values-dilemma-in-oracle-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!