Peter Larsson Blog

Patron Saint of Lost Yaks

NOT IN not equal to <>

Hi!

I am between session of 24 hour of PASS right now, so I just post this piece of code I helped out with on a forum.
The original poster was amazed that

Col1 <> 'Some value'

didn't return same records as

Col1 NOT IN ('Some value')

See this example code to understand the implications of fiddling with SET ANSI_NULLS option setting.


declare
@sample table
        (
            d varchar(200)
        )

Insert  @sample
select  'cancelled' union all
select  null

-- Try 1
set ansi_nulls off

select  d as [Try 1, <>, ANSI_NULLS off]
from    @sample
where   d <> 'cancelled'

select  d as [Try 1, NOT IN, ANSI_NULLS off]
from    @sample
where   d not in ('cancelled')

-- Try 2
set ansi_nulls on

select  d as [Try 2, <>, ANSI_NULLS on]
from    @sample
where   d <> 'cancelled'

select  d as [Try 2, NOT IN, ANSI_NULLS on]
from    @sample
where   d not in ('cancelled')

 

Legacy Comments


Peter Cwik
2009-09-08
re: NOT IN not equal to <>
According to BOL

For a script to work as intended, regardless of the ANSI_NULLS database option or the setting of SET ANSI_NULLS, use IS NULL and IS NOT NULL in comparisons that might contain null values.


Peso
2009-09-08
re: NOT IN not equal to <>
The issue is not to get the NULL values. The issue OP had was why NULL values were returned at all.

Dayana
2011-08-23
re: NOT IN not equal to <>
Phenomenal bkredaown of the topic, you should write for me too!

mhstyhcfl
2011-08-27
re: NOT IN not equal to <>
bLiVei huqdjakfufmc