Is there any difference between IS NULL and =NULL

SqlSql ServerSql Server-2005

Sql Problem Overview


I am surprised to see that IS NULL and =NULL are yielding different results in a select query. What is difference between them? When to use what. I would be glad if you can explain me in detail.

Sql Solutions


Solution 1 - Sql

= NULL is always unknown (this is piece of 3 state logic), but WHERE clause treats it as false and drops from the result set. So for NULL you should use IS NULL

Reasons are described here: https://stackoverflow.com/questions/1843451/why-does-null-null-evaluate-to-false-in-sql-server

Solution 2 - Sql

To add to existing answers, it depends whether you have ANSI_NULLS on or not, when using "= NULL".

-- This will print TRUE
SET ANSI_NULLS OFF;
IF NULL = NULL
    PRINT 'TRUE'
ELSE
    PRINT 'FALSE'

-- This will print FALSE
SET ANSI_NULLS ON;
IF NULL = NULL
    PRINT 'TRUE'
ELSE
    PRINT 'FALSE'

Solution 3 - Sql

There is a difference between IS NULL and = NULL and this is because of the three-valued-logic of SQL:

https://en.wikipedia.org/wiki/Null_%28SQL%29#Three-valued_logic_.283VL.29

Extract of a relevant paragraph:

> Challenges > > Null has been the focus of controversy and a source of > debate because of its associated three-valued logic (3VL), special > requirements for its use in SQL joins, and the special handling > required by aggregate functions and SQL grouping operators. Computer > science professor Ron van der Meyden summarized the various issues as: > "The inconsistencies in the SQL standard mean that it is not possible > to ascribe any intuitive logical semantics to the treatment of nulls > in SQL." Although various proposals have been made for resolving these > issues, the complexity of the alternatives has prevented their > widespread adoption.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsatyaView Question on Stackoverflow
Solution 1 - SqlAndreyView Answer on Stackoverflow
Solution 2 - SqlAdaTheDevView Answer on Stackoverflow
Solution 3 - SqlMarkus WinandView Answer on Stackoverflow