Why NOT IN (NULL) Always returns nothing

前端 未结 3 2024
不知归路
不知归路 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:07

    Because value equals NULL is not defined, and will never evaluate to True. Check This post on bad practices. Don't use IN and NULL, use EXISTS to test for at least one row where something exists.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-24 13:31

    Your query evaluates to calname <> null , which results in UNKNOWN.

    Change your query to this ,

    SELECT * FROM dbo.Calendars WHERE calname IS NOT NULL;
    
    0 讨论(0)
提交回复
热议问题