Why NOT IN (NULL) Always returns nothing

前端 未结 3 2047
不知归路
不知归路 2021-01-24 12:33

I have following table:

And following simple query:

SELECT * FROM dbo.Calendars WHERE calname NOT IN(NULL)

My question is why always <

3条回答
  •  独厮守ぢ
    2021-01-24 13:18

    NULL is treated differently to other values in most databases. For instance, this predicate will never be true:

    WHERE foo = NULL
    

    whereas this predicate is true if the value of foo is indeed NULL:

    WHERE foo IS NULL
    

    To your problem, if you only wish to check if calname is not null, use the following predicate:

    WHERE calname IS NOT NULL
    

    If on the other hand you have a set of values, of which NULL is one of those values (say [1,2,3,4,NULL]), and you still want to use the NOT IN syntax, you have to do it like this:

    WHERE calname IS NOT NULL AND calname NOT IN(1, 2, 3, 4)
    

    EDIT: A further way of doing this, if you are constrained to use the NOT IN syntax is to COALESCE the column calname into a value that you definitely know is not stored in that column. For instance, if calname can only take positive integer values, then we can do this instead:

    WHERE COALESCE(calname, -1) NOT IN (-1)
    

提交回复
热议问题