In the SQL NULL
stands for "value unknown".
If you say x! = NULL, you say: "this is the value of x, not equal to the unknown value." Well, since we donβt know what an unknown value is, we donβt know if x is equal to it or not. Therefore, the answer is "I do not know."
Similarly:
x = NULL OR 1=2 -- Unknown. 1=2 is not true, but we don't know about x=NULL x = NULL OR 1=1 -- True. We know that at least 1=1 is true, so the OR is fulfulled regardless. x = NULL AND 1=1 -- Unknown. We want them both to be true to fulful the AND x = NULL AND 1=2 -- False. We know 1=2 is false, so the AND is not fulfilled regardless.
Besides
-- Neither statement will select rows where x is null select x from T where x = 1 select x from T where x != 1
The only way to check for zero is to ask the question "is it true that we do not know what the value of x is". It has a yes or no answer and uses the IS
keyword.
If you want zeros to be treated as zero or another value, you can use the COALESCE
or ISNULL
.
COALESCE(NULL, 1) -- 1 COALESCE(NULL, NULL, 1) -- Also 1 COALESCE(x, y, z, 0) -- x, unless it is null, then y, unless it is null, then z, unless it is null in which case 0.
source share