Testing for inequality in T-SQL

前端 未结 4 968
悲哀的现实
悲哀的现实 2020-11-30 08:49

I\'ve just come across this in a WHERE clause:

AND NOT (t.id = @id)

How does this compare with:

AND t.id != @id


        
相关标签:
4条回答
  • 2020-11-30 08:57

    Just a little adjustement fors those who come later:

    The equality operator generate a unknow value when there is a null and the unknown value is treated a false. Not (unknown) is unknown

    In the example below I'll try to say if a couple (a1, b1) is equal to (a2, b2). Note that each columns has 3 values 0, 1 and NULL.

    DECLARE @t table (a1 bit, a2 bit, b1 bit, b2 bit)
    
    Insert into @t (a1 , a2, b1, b2) 
    values( 0 , 0 , 0 , NULL )
    
    select 
    a1,a2,b1,b2,
    case when (
        (a1=a2 or (a1 is null and a2 is null))
    and (b1=b2 or (b1 is null and b2 is null))
    )
    then 
    'Equal'
    end,
    case when not (
        (a1=a2 or (a1 is null and a2 is null))
    and (b1=b2 or (b1 is null and b2 is null))
    )
    then 
    'not Equal'
    end,
    case when (
        (a1<>a2 or (a1 is null and a2 is not null) or (a1 is not null and a2 is null))
    or (b1<>b2 or (b1 is null and b2 is not null) or (b1 is not null and b2 is null))
    )
    then 
    'Different'
    end
    from @t
    

    Note that here we expect results :

    • Equal to be null
    • not equal to be not equal
    • different to be difFerent

    but we get another result

    • Equal is null OK
    • Not Equal is null ???
    • Different is different
    0 讨论(0)
  • 2020-11-30 08:57

    There will be no performance hit, both statements are perfectly equal.

    HTH

    0 讨论(0)
  • 2020-11-30 09:05

    These 3 will get the same exact execution plan

    declare @id varchar(40)
    select @id = '172-32-1176'
    
    select * from authors
    where au_id <> @id
    
    select * from authors
    where au_id != @id
    
    select * from authors
    where not (au_id = @id)
    

    It will also depend on the selectivity of the index itself of course. I always use au_id <> @id myself

    0 讨论(0)
  • 2020-11-30 09:06

    Note that the != operator is not standard SQL. If you want your code to be portable (that is, if you care), use <> instead.

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