Strange results from NOT IN subquery

后端 未结 2 1755
醉酒成梦
醉酒成梦 2021-01-23 11:19

I have this simple query:

SELECT COUNT(SalesOrderId)
FROM SalesOrder

It gives a result of 14000

Then I have

SELECT COUN         


        
相关标签:
2条回答
  • 2021-01-23 11:21

    NOT IN with NULL could be tricky.

    Let's unwrap it:

    col IN (1,2,3, NULL)
    <=>
    (col = 1) OR (col = 2) OR (col = 3) OR (col = NULL)
    

    For now everything is ok. But it isn't. We cannot compare directly value to NULL because the result is unknown.

    Let's check negated condition:

    col NOT IN (1,2,3,NULL)
    <=>
    (col != 1) AND (col != 2) AND (col != 3) AND (col != NULL) 
                                                  -- here is the problem
    

    LiveDemo

    To sum up last condition is always not true. That is why you get 0 records.


    When you use NOT IN make sure that you do not compare with NULL value.

    0 讨论(0)
  • 2021-01-23 11:28
    SELECT COUNT_BIG(s.SalesOrderId)
    FROM dbo.SalesOrder s
    WHERE s.SalesOrderId NOT IN
        (
            SELECT n.New_DSheetId
            FROM dbo.New_dealsheet n
            WHERE n.New_DSheetId IS NOT NULL
        )
    
    0 讨论(0)
提交回复
热议问题