NULL values are excluded. Why?

前端 未结 4 1849
谎友^
谎友^ 2020-12-16 11:47

This is about a bizarre behaviour I found in Microsoft Sql Server. Please correct me if I\'m wrong.

SELECT COUNT(*) FROM TABLEA 
WHERE [Column1] IS NULL;


        
相关标签:
4条回答
  • 2020-12-16 11:58

    Another example of taking care when dealing with nulls

    I'm just agreeing with Sumo - why not just change the view to:

    CREATE VIEW VIEWB AS 
    SELECT * FROM TABLEA AS t1 
    WHERE 
        t1.[Column1] NOT IN ('Cross/Up sell', 'Renegotiation', 'Renewal')  
        OR
        t1 IS NULL 
    

    an alternative might be the following which I've added to SQL FIDDLE

    CREATE VIEW VIEWB AS 
    SELECT * FROM TABLEA AS t1 
    WHERE 
        1 = CASE 
              WHEN ISNULL(t1.[Column1],'x') NOT IN ('Cross/Up sell', 'Renegotiation', 'Renewal') THEN 1
              ELSE 0
            END
    
    0 讨论(0)
  • 2020-12-16 12:03

    SQL uses three valued logic.

    t1.[Column1] NOT IN ('Cross/Up sell', 'Renegotiation', 'Renewal') 
    

    is equivalent to

    t1.[Column1] <> 'Cross/Up sell' AND  
    t1.[Column1] <> 'Renegotiation' AND 
    t1.[Column1] <>  'Renewal')
    

    When t1.[Column1] is NULL this expression evaluates to UNKNOWN rather than TRUE so these rows are not returned.

    The only time NULL NOT IN ( ... ) will be returned is if the NOT IN clause evaluates to an empty set.

    0 讨论(0)
  • 2020-12-16 12:08

    This is actually a common mistake made with SQL Server in treating NULL as a value. By default, it's treated as UNKNOWN, as documented here. So, in your view, you also need to include an OR t1.[Column1] IS NULL.

    You can change this behavior by calling SET ANSI_NULLS OFF. It is not recommended to use this, however, as the feature is deprecated as pointed out by @Martin Smith.

    This is not a SQL Server specific issue, however. It's part of the ANSI SQL standard.

    0 讨论(0)
  • 2020-12-16 12:11

    Best answer would be just to use below condition in where clause

    ISNULL(t1.[Column1],'') NOT IN ('Cross/Up sell', 'Renegotiation', 'Renewal')

    0 讨论(0)
提交回复
热议问题