SQL では、NULL
「不明な値」を意味します。
x != NULL と言うと、「x の値が未知の値と等しくない」ということになります。未知の値が何であるかがわからないので、x がそれと等しいかどうかもわかりません。ですから、答えは「わかりません」です。
同様に:
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.
また
-- Neither statement will select rows where x is null
select x from T where x = 1
select x from T where x != 1
null をチェックする唯一の方法は、「x の値がわからないというのは本当ですか」と明確に尋ねることです。これには、はいまたはいいえの答えがあり、IS
キーワードを使用します。
null をゼロまたは別の値として扱いたい場合は、COALESCE
orISNULL
関数を使用できます。
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.