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のレコードがちゃんと返ってきました。