MySQL mystery: Null value is not different from non-null string

前端 未结 5 650
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 16:25

Why is this query returning 0 rows?

select t.f1, t.f2
from (select null f1, \'a\' f2 from dual) t
where t.f1<>t.f2;

This is a distill

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-20 16:37

    Exactly. NULL represents an unknown value, not any specific value (it is not the same as NULL in C, or nil in Ruby, etc.) In SQL, if you compare something to the unknown value, the result is also unknown. And you will not get the rows where WHERE condition is unknown.

    Try this:

    SELECT NULL <> 2;
    

    and you will see NULL as result.

    Try this:

    SELECT * FROM t WHERE NULL;
    

    and no rows will come out, even if the table t is huge.

    If you really need what you said you wanted (and I am not advocating this), you can do something like this:

    SELECT T.f1, T.f2
    FROM (SELECT NULL f1, 'a' f2) T
    WHERE ((T.f1 IS NULL OR T.f2 IS NULL)
        AND (T.f1 IS NOT NULL OR T.f2 IS NOT NULL))
        OR T.f1 <> T.f2
    

提交回复
热议问题