Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the results for 1 = NULL and 1 != NULL the same?

Tags:

sql

database

null

The following

IF 1 = NULL 
    BEGIN
        SELECT  'A'
    END
ELSE 
    BEGIN
        SELECT  'B'
    END

Returns the result B as expected

Here's where things get really interesting

IF 1 != NULL 
    BEGIN
        SELECT  'A'
    END
ELSE 
    BEGIN
        SELECT  'B'
    END

Also returns B

Why is this the case?

like image 295
Seattle Leonard Avatar asked May 16 '13 21:05

Seattle Leonard


2 Answers

Neither IF statement is true. NULL is neither equal to something nor not equal to something. Something either IS NULL or IS NOT NULL.

like image 67
John Avatar answered Nov 04 '22 00:11

John


Agree with what everyone else has already said. Simply commenting from another angle, if you try setting ansi_nulls to off, you may get what you expected:

set ansi_nulls off

if 1 = null
    select 'a'
else
    select 'b' -- Returned


if 1 != null
    select 'a' -- Returned
else
    select 'b'

More info from Books Online:

When SET ANSI_NULLS is OFF, the Equals (=) and Not Equal To (<>) comparison operators do not follow the ISO standard. A SELECT statement that uses WHERE column_name = NULL returns the rows that have null values in column_name. A SELECT statement that uses WHERE column_name <> NULL returns the rows that have nonnull values in the column. Also, a SELECT statement that uses WHERE column_name <> XYZ_value returns all rows that are not XYZ_value and that are not NULL.

That's ansi_nulls off explained. However, don't be tempted to simply switch it off because:

In a future version of SQL Server, ANSI_NULLS will always be ON and any applications that explicitly set the option to OFF will generate an error. Avoid using this feature in new development work, and plan to modify applications that currently use this feature.

Follow the below recommendation instead:

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.

if 1 is null
    select 'a'
else
    select 'b' -- Returned


if 1 is not null
    select 'a' -- Returned
else
    select 'b'
like image 34
Louie Bao Avatar answered Nov 04 '22 00:11

Louie Bao