MySQL comparison with null value

2019-01-11 09:41发布

I have a column called CODE in a MySQL table which can be NULL. Say I have some rows with CODE='C' which I want to ignore in my select result set. I can have either CODE=NULL or CODE!='C' in my result set.

The following query does not return a row with CODE as NULL:

SELECT * from TABLE where CODE!='C'

But this query works as expected and I know it is the right way to do it.

SELECT * from TABLE where CODE IS NULL OR CODE!='C'

My question is why does having only CODE!='C' does not return rows where CODE=NULL? Definitely 'C' is not NULL. We are comparing no value to a character here. Can someone throw some light as why it doesn't work that way?

5条回答
The star\"
2楼-- · 2019-01-11 10:20

select * from user where application_id='1223333344' and name is null;

查看更多
太酷不给撩
3楼-- · 2019-01-11 10:26
SELECT * 
FROM `table_name` 
WHERE IFNULL(`column_name` != 'C', TRUE)
查看更多
萌系小妹纸
4楼-- · 2019-01-11 10:34

In MySQL, NULL is considered as a 'missing, unknown value', as opposed to no value. Take a look at this MySQL Reference on NULL.

Any arithmetic comparison with NULL does not return true or false, but returns NULL instead., So, NULL != 'C' returns NULL, as opposed to returning true.

Any arithmetic comparison with 'NULL' will return false. To check this in SQL:

SELECT IF(NULL=123,'true','false') 

To check NULL values we need to use IS NULL & IS NOT NULL operator.

查看更多
时光不老,我们不散
5楼-- · 2019-01-11 10:39

In SQL, the NULL value is a special value, not comparable with any other one. The result of a direct comparison with a value is either always FALSE or NULL, depending on the implementation.

To test a null value you should use IS NULL and IS NOT NULL.

查看更多
The star\"
6楼-- · 2019-01-11 10:45

Based on my tests and the documentation here: http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html

You can compare null and get a boolean result using <=>

For example:

select x <=> y; 
or
select @x <=> @y;

This also compares string vs null, string vs string, etc.

查看更多
登录 后发表回答