isnull vs is null

后端 未结 10 1238
闹比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:37

    They don't mean the same thing.

    name is not null 
    

    This checks for records where the name field is null

    isnull(name,'') <> name  
    

    This one changes the value of null fields to the empty string so they can be used in a comparision. In SQL Server (but not in Oracle I think), if a value is null and it is used to compare equlaity or inequality it will not be considered becasue null means I don't know the value and thus is not an actual value. So if you want to make sure the null records are considered when doing the comparision, you need ISNULL or COALESCE(which is the ASCII STANDARD term to use as ISNULL doen't work in all databases).

    What you should be looking at is the differnece between

    isnull(a.name,'') <> b.name  
    

    a.name <> b.name

    then you will understand why the ISNULL is needed to get correct results.

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

    Others have pointed out the functional difference. As to the performance issue, in Postgres I've found that -- oh, I should mention that Postgres has a function "coalesce" that is the equivalent of the "isnull" found in some other SQL dialects -- but in Postgres, saying

    where coalesce(foobar,'')=''
    

    is significantly faster than

    where foobar is null or foobar=''
    

    Also, it can be awesomely dramatically faster to say

     where foobar>''
    

    over

    where foobar!=''
    

    A greater than test can use the index and thus skip over all the blanks, while a not-equal test has to do a full file read. (Assuming you have an index on the field and no other index is used in preference.)

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

    Also if you want to make use of the index on that column, use

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

    It is to handle both the empty string and NULL. While it is good to be able to do with with one statement, isnull is proprietary syntax. I would write this using portable Standard SQL as

    NULLIF(name, '') IS NOT NULL
    
    0 讨论(0)
提交回复
热议问题