NULLとインデックスについて
MySQLでindexが使われない場合に
NULLはインデックスに含まれない
という記述をいろいろな場所で見かけるが、実際はヌルがあってもインデックスが使用される。
リファレンスを見ても
column_name IS NULL を使用した検索では、column_name にインデックスが張られている場合にインデックスが使用されます。
との記述があります。
実際に試してみると、
カラムのステータス
mysql> SHOW COLUMNS FROM index_test; +-------+---------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+---------+------+-----+---------+----------------+ | id | int(11) | | PRI | NULL | auto_increment | | test1 | int(11) | YES | MUL | NULL | | | test2 | int(11) | | | 0 | | +-------+---------+------+-----+---------+----------------+ 3 rows in set (0.00 sec)
テーブルのレコード
mysql> select * from index_test; +----+-------+-------+ | id | test1 | test2 | +----+-------+-------+ | 1 | 1 | 1 | | 2 | 2 | 2 | | 3 | 3 | 3 | | 4 | 4 | 4 | | 5 | 5 | 5 | | 6 | 6 | 6 | | 7 | 7 | 7 | | 8 | 8 | 8 | | 9 | 9 | 9 | | 10 | NULL | 0 | +----+-------+-------+ 10 rows in set (0.01 sec)
実際にインデックスが使用されていることがわかる。
mysql> explain select * from index_test where test1=5; +----+-------------+------------+------+---------------+-------+---------+-------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+------+---------------+-------+---------+-------+------+-------------+ | 1 | SIMPLE | index_test | ref | test1 | test1 | 5 | const | 1 | Using where | +----+-------------+------------+------+---------------+-------+---------+-------+------+-------------+ 1 row in set (0.00 sec)
ヌルのときもインデックスが使用されている。
mysql> explain select * from index_test where test1 is null; +----+-------------+------------+------+---------------+-------+---------+-------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+------------+------+---------------+-------+---------+-------+------+-------------+ | 1 | SIMPLE | index_test | ref | test1 | test1 | 5 | const | 1 | Using where | +----+-------------+------------+------+---------------+-------+---------+-------+------+-------------+ 1 row in set (0.00 sec)
しっかりとインデックスが使用されていることがわかります。