I\'m not asking if it does. I know that it doesn\'t.
I\'m curious as to the reason. I\'ve read support docs such as as this one on Working With Nu
NULL is unknown. It is neither true nor false so when you are comparing anything to unknown, the only answer is "unknown" Much better article on wikipedia http://en.wikipedia.org/wiki/Null_(SQL)
Why don't you use the isnull function?
@where = "where GroupId = "+ isnull(@groupId,"null")
The reason why it's off by default is that null
is really not equal to null
in a business sense. For example, if you were joining orders and customers:
select * from orders o join customers c on c.name = o.customer_name
It wouldn't make a lot of sense to match orders with an unknown customer with customers with an unknown name.
Most databases allow you to customize this behaviour. For example, in SQL Server:
set ansi_nulls on
if null = null
print 'this will not print'
set ansi_nulls off
if null = null
print 'this should print'
NULL doesn't equal NULL. It can't equal NULL. It doesn't make sense for them to be equal.
A few ways to think about it:
Imagine a contacts database, containing fields like FirstName
, LastName
, DateOfBirth
and HairColor
. If I looked for records WHERE DateOfBirth = HairColor
, should it ever match anything? What if someone's DateOfBirth
was NULL, and their HairColor
was too? An unknown hair color isn't equal to an unknown anything else.
Let's join the contacts table with purchases and product tables. Let's say I want to find all the instances where a customer bought a wig that was the same color as their own hair. So I query WHERE contacts.HairColor = product.WigColor
. Should I get matches between every customer I don't know the hair color of and products that don't have a WigColor
? No, they're a different thing.
Let's consider that NULL is another word for unknown. What's the result of ('Smith' = NULL)
? The answer is not false, it's unknown. Unknown is not true, therefore it behaves like false. What's the result of (NULL = NULL)
? The answer is also unknown, therefore also effectively false. (This is also why concatenating a string with a NULL value makes the whole string become NULL -- the result really is unknown.)
Because in ANSI SQL, null means "unknown", which is not a value. As such, it doesn't equal anything; you can just evaluate the value's state (known or unknown).
Equality is something that can be absolutely determined. The trouble with null
is that it's inherently unknown. If you follow the truth table for three-value logic, null
combined with any other value is null
- unknown. Asking SQL "Is my value equal to null?" would be unknown every single time, even if the input is null. I think the implementation of IS NULL
makes it clear.