Strange results from NOT IN subquery

后端 未结 2 1754
醉酒成梦
醉酒成梦 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.

提交回复
热议问题