I am using the following query:
select count(*) from Table1 where CurrentDateTime>'2012-05-28 15:34:02.403504' and Error not in ('Timeout','Connection Error');
Surprisingly, this statement doesnot include the rows having Error value as NULL.My intention is to filter only rows with Error value as ‘Timeout’ (or) ‘Connection Error’. I need to give an additional condition( OR Error is NULL) to retrieve the correct result.
Why is MYSQL filtering out results with NULL values?
I thought that IN keyword would return a boolean result (1/0) and now i understand that some MYSQL keywords doesnt return boolean values,it might return NULL too….but Why is it treating NULL as special?
This :
is semantically equivalent to:
Rules about null comparison applies to IN too. So if the value of Error is NULL, the database can’t make the expression true.
To fix, you could do this:
Or better yet:
Or more better yet:
ORdoesn’t short-circuit, CASE can somehow short-circuit your queryPerhaps a concrete example could illustrate why
NULL NOT IN expressionreturns nothing:Given this data: http://www.sqlfiddle.com/#!2/0d5da/11
And you do this expression:
That will output ‘hi’ only.
The NOT IN is translated as:
NULL <> 'bruce'can’t be determined, not even true, not even falseNULL <> 'banner'can’t be determined, not even true not even falseSo the null value expression, effectively resolved to:
In fact, if your RDBMS supports boolean on SELECT(e.g. MySQL, Postgresql), you can see why: http://www.sqlfiddle.com/#!2/d41d8/828
That returns null.
This returns null too:
Given you are using
NOT IN, which is basically an AND expression.Results to NULL. So it’s like you are doing a: http://www.sqlfiddle.com/#!2/0d5da/12
Nothing will be returned