isnull vs is null

后端 未结 10 1237
闹比i
闹比i 2020-12-06 00:13

I have noticed a number of queries at work and on SO are using limitations in the form:

isnull(name,\'\') <> \'\'

Is there a particul

相关标签:
10条回答
  • 2020-12-06 00:25
    isnull(name,'') <> name
    

    Well I can see them using this because this way if the name doesn't match or is null it returns as a failed comparison. This really means: name is null or name <> name

    Where as this one name is not null just checks to see if the name is null.

    0 讨论(0)
  • 2020-12-06 00:25

    These two queries are not the same. For example, I do not have a middle name, this is a known fact, which can be stored as

    MiddleName=''
    

    However, if we don't know someone's middle name, we can store NULL. So, ISNULL(MiddleName, '') means "persons without known middle names".

    0 讨论(0)
  • 2020-12-06 00:28
    is not null
    

    Will only check if the field is not null. If the field contains an empty string, then the field is no longer null.

    isnull(name, '') <> name
    

    Checks for both a null and an empty string.

    0 讨论(0)
  • 2020-12-06 00:28

    I apparently misread your question. So let me strike my first answer and try this one:

    isnull(name,'') <> ''
    

    is a misguided shortcut for

    name is not null and name <> ''
    
    0 讨论(0)
  • 2020-12-06 00:30
    where isnull(name,'') <> ''
    

    is equivalent to

    where name is not null and name <> '' 
    

    which in turn is equivalent to

    where name <> ''
    

    (if name IS NULL that final expression would evaluate to unknown and the row not returned)

    The use of the ISNULL pattern will result in a scan and is less efficient as can be seen in the below test.

    SELECT ca.[name],
           [number],
           [type],
           [low],
           [high],
           [status]
    INTO   TestTable
    FROM   [master].[dbo].[spt_values]
           CROSS APPLY (SELECT [name]
                        UNION ALL
                        SELECT ''
                        UNION ALL
                        SELECT NULL) ca 
    
    
    CREATE NONCLUSTERED INDEX IX_TestTable ON dbo.TestTable(name)
    
    GO
    
    
    SELECT name FROM TestTable WHERE isnull(name,'') <> ''
    
    SELECT name FROM TestTable WHERE name is not null and name <> ''
    /*Can be simplified to just WHERE name <> '' */
    

    Which should give you the execution plan you need.

    0 讨论(0)
  • 2020-12-06 00:36

    isnull(name,'') <> :name is shorthand for (name is null or name <> :name) (assuming that :name never contains the empty string, thus why shorthands like this can be bad).

    Performance-wise, it depends. or statements in where clauses can give extremely bad performance. However, functions on columns impair index usage. As usual: profile.

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