1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

SQLでNULLを条件にする時は"IS NULL"を使う

Posted at

SQLの条件文でカラムがNULLであることを指定する際には、"= NULL"ではなくて"IS NULL"を使うそうですが、それの理由について調べていてなるほど思ったのでメモ書きしておきます。

IS NULLを使う理由

こちらの記事がとても参考になりました。ありがとうございます。

簡潔に説明すると、SQLにおいてNULLというのはNULLという名前の固有値ではなく、「何か分からないもの」らしいです。
なので、NULLと何かを比較するのは「何か分からないもの」と何かを比較するということになり、分からないものとの比較結果は「分からない」ので、結果が0件になるということです。
なので、"NULL = NULL"という式もFALSEになります。(分からないものと分からないものを比較した結果は「分からない」ため。)

そして、"IS NULL"という演算子は「対象が未知もしくは適用不能」であるかを確かめられるので、NULLを条件に検索する際はこの演算子を使えばいいみたいです。

実際に確認

実際にテーブルを作って確かめてみました。

テーブル定義

mysql> SHOW COLUMNS FROM users;
+-------+------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra          |
+-------+------+------+-----+---------+----------------+
| id    | int  | NO   | PRI | NULL    | auto_increment |
| name  | text | YES  |     | NULL    |                |
+-------+------+------+-----+---------+----------------+

レコード

mysql> SELECT * FROM users;
+----+------+
| id | name |
+----+------+
|  1 | NULL |
|  2 | TOMO |
+----+------+

"= NULL"で検索

mysql> SELECT * FROM users WHERE name = NULL;
Empty set (0.00 sec)

結果は0件ですね。

"IS NULL"で検索

mysql> SELECT * FROM users WHERE name IS NULL;
+----+------+
| id | name |
+----+------+
|  1 | NULL |
+----+------+

nameがNULLのレコードがちゃんと返ってきました。

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?