An
instatement will be parsed identically tofield=val1 or field=val2 or field=val3. Putting a null in there will boil down tofield=nullwhich won't work.
(Comment by Marc B)
I would do this for clairity
SELECT *
FROM tbl_name
WHERE
(id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL)
Answer from Daniel A. White on Stack OverflowSQL's NULL values are confusing – understanding how they work
A tricky one that catches me from time to time is the effect of a null in a subquery that you're doing "not in" operator on:
select a.* from A a where a.f1 not in (select b.f2 from B b where ...)
If the query for B produces any nulls, you'll always get no results from the query for A, regardless of the other content in A and B. That's because the query engine can't be sure any particular value is not in the list, because any null in the subquery is treated like an unknown that could stand for anything. So it returns null or false at each check of the not-in condition, and a null final result in a where clause won't have a record making it into the results, only positively true values would.
More on reddit.comReplace nulls values in sql using select statement in mysql? - Stack Overflow
What is the best way to handle null in the aggregation function with the calculations?
why am I having null in a sum in SQL?
What does IS NULL do in SQL?
What is the difference between a null cell and an empty cell in SQL?
Why doesn't WHERE column = NULL work?
An
instatement will be parsed identically tofield=val1 or field=val2 or field=val3. Putting a null in there will boil down tofield=nullwhich won't work.
(Comment by Marc B)
I would do this for clairity
SELECT *
FROM tbl_name
WHERE
(id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL)
Your query fails due to operator precedence. AND binds before OR!
You need a pair of parentheses, which is not a matter of "clarity", but pure logic necessity.
SELECT *
FROM tbl_name
WHERE other_condition = bar
AND another_condition = foo
AND (id_field IN ('value1', 'value2', 'value3') OR id_field IS NULL);
The added parentheses prevent AND binding before OR. If there were no other WHERE conditions (no AND) you would not need additional parentheses. The accepted answer is misleading in this respect.
You have a lot of options for substituting NULL values in MySQL:
CASE
select case
when fieldname is null then '123'
else fieldname end as fieldname
from tablename
COALESCE
select coalesce(fieldname, '123') as fieldname
from tablename
IFNULL
select ifnull(fieldname, '123') as fieldname
from tablename
There is a statement called IFNULL, which takes all the input values and returns the first non NULL value.
example:
select IFNULL(column, 1) FROM table;
http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull