1 row in set
Time: 0.002s
mysql root@localhost:cygwin> select * from table_3 where user_name = null\G
0 rows in set
Time: 0.002s
mysql root@localhost:cygwin> desc select * from table_3 where user_name = 'zhaoliu_2_1'\G
***************************[ 1. row ]***************************
id | 1
select_type | SIMPLE
table | table_3
type | ref
possible_keys | IDX_test
key | IDX_test
key_len | 23
ref | const
rows | 1
Extra | Using where
1 row in set
Time: 0.006s
mysql root@localhost:cygwin> desc select * from table_3 where user_name = null\G
***************************[ 1. row ]***************************
id | 1
select_type | SIMPLE
table | None
type | None
possible_keys | None
key | None
key_len | None
ref | None
rows | None
Extra | Impossible WHERE noticed after reading const tables
1 row in set
Time: 0.002s
mysql root@localhost:cygwin> desc select * from table_3 where user_name is null\G
***************************[ 1. row ]***************************
id | 1
select_type | SIMPLE
table | table_3
type | ref
possible_keys | IDX_test
key | IDX_test
key_len | 23
ref | const
rows | 1
Extra | Using where
1 row in set
Time: 0.002s
mysql root@localhost:cygwin>
(5)Null 列需要更多的存储空间:需要一个额外字节作为判断是否为 NULL 的标志位
alter table table_3 add index idx_user_name (user_name);
alter table table_2 add index idx_user_name (user_name);
explain select * from table_2 where user_name='zhaoliu_2_1';
explain select * from table_3 where user_name='zhaoliu_2_1';
可以看到同样的 varchar(20) 长度,table_2 要比 table_3 索引长度大,这是因为:
两张表的字符集不一样,且字段一个为 NULL 一个非 NULL。
key_len 的计算规则和三个因素有关:数据类型、字符编码、是否为 NULL
key_len 62 == 20*3(utf8 3字节) + 2 (存储 varchar 变长字符长度 2字节,定长字段无需额外的字节)
key_len 83 == 20*4(utf8mb4 4字节) + 1 (是否为 Null 的标识) + 2 (存储 varchar 变长字符长度 2字节,定长字段无需额外的字节)
所以说索引字段最好不要为NULL,因为NULL会使索引、索引统计和值更加复杂,并且需要额外一个字节的存储空间。基于以上这些理由和原因,我想咱们不用 Null 的理由应该是够了。
Refer:
[1] 为什么每个开发哥哥都喜欢用NULL值?
http://bit.ly/2u3GKZI
[2] 优化 SQL 查询:如何写出高性能SQL语句
http://bit.ly/2t2ehng
[3] 或许你不知道的10条SQL技巧
https://mp.weixin.qq.com/s/dGcgts4NNTmVQNRT-j2MZw