Not In operator eliminates NULL values rows in a table

孤街醉人 提交于 2020-08-08 05:28:26

问题


I would like to retrieve all rows with values except 1,2,3,4,5 in my COLUMNA in TABLEA .

SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5)

But this eliminates the rows with NULL values in COLUMNA too.

I don't want to eliminate NULL values rows and would like to include those rows in the resultset.

Alternatively, I can try below query for the same

SELECT * FROM TABLEA WHERE COLUMNA NOT IN (1,2,3,4,5) OR COLUMNA  IS NULL.

But I would like to know, why is it necessary to add this OR condition?


回答1:


Why is the additional necessary?

NULL comparisons almost always results in NULL, rather than true or false. A WHERE clause filters out all non-true values, so they get filtered out.

This is how SQL defines NULL. Why is NULL defined like this?

NULL does not mean "missing" in SQL. It means "unknown". So, the result of <unknown> not in (1, 2, 3, 4, 5) is "unknown", because the value could be 1 or it might be 0. Hence it gets filtered.

I will also note that the SQL standard includes NULL-safe comparisons, IS NOT DISTINCT FROM and IS DISTINCT FROM corresponding to = and <> respectively. These treat NULL as just "any other value", so two NULL values are considered equal. However, there is no construct for NULL-safe IN and NOT IN, as far as I know.




回答2:


Try the following:

SELECT * FROM TABLEA WHERE ISNULL(COLUMNA,0) NOT IN (1,2,3,4,5)



来源:https://stackoverflow.com/questions/56394498/not-in-operator-eliminates-null-values-rows-in-a-table

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