MySQL,一千个不用 Null 的理由

https://www.itcodemonkey.com/article/1405.html

 

MySQL,一千个不用 Null 的理由

2017-11-30 09:32:48 分类:数据库开发

来自:xrzs的博客

港真,Null 貌似在哪里都是个头疼的问题,比如 Java 里让人头疼的 NullPointerException,为了避免猝不及防的空指针异常,千百年来程序猿们不得不在代码里小心翼翼的各种 if 判断,麻烦而又臃肿,为此 java8 引入了 Optional 来避免这一问题。

下面咱们要聊的是 MySQL 里的 null,在大量的 MySQL 优化文章和书籍里都提到了字段尽可能用NOT NULL,而不是NULL,除非特殊情况。但却都只给结论不说明原因,犹如鸡汤不给勺子一样,让不少初学者对这个结论半信半疑或者云里雾里。本文今天就详细的剖析下使用 Null 的原因,并给出一些不用 Null 的理由。

 

1、NULL 为什么这么多人用?

  • NULL是创建数据表时默认的,初级或不知情的或怕麻烦的程序员不会注意这点。

  • 很多人员都以为not null 需要更多空间,其实这不是重点。

  • 重点是很多程序员觉得NULL在开发中不用去判断插入数据,写sql语句的时候更方便快捷。

 

2、是不是以讹传讹?

MySQL 官网文档:

NULL columns require additional space in the rowto record whether their values are NULL. For MyISAM tables, each NULL columntakes one bit extra, rounded up to the nearest byte.

Mysql难以优化引用可空列查询,它会使索引、索引统计和值更加复杂。可空列需要更多的存储空间,还需要mysql内部进行特殊处理。可空列被索引后,每条记录都需要一个额外的字节,还能导致MYisam 中固定大小的索引变成可变大小的索引。

—— 出自《高性能mysql第二版》

照此分析,还真不是以讹传讹,这是有理论依据和出处的。

 

3、给我一个不用 Null 的理由?

  • (1)所有使用NULL值的情况,都可以通过一个有意义的值的表示,这样有利于代码的可读性和可维护性,并能从约束上增强业务数据的规范性。

  • (2)NULL值到非NULL的更新无法做到原地更新,更容易发生索引分裂,从而影响性能。

注意:但把NULL列改为NOT NULL带来的性能提示很小,除非确定它带来了问题,否则不要把它当成优先的优化措施,最重要的是使用的列的类型的适当性。

  • (3)NULL值在timestamp类型下容易出问题,特别是没有启用参数explicit_defaults_for_timestamp

  • (4)NOT IN、!= 等负向条件查询在有 NULL 值的情况下返回永远为空结果,查询容易出错

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

create table table_2 (

     `id` INT (11) NOT NULL,

    user_name varchar(20) NOT NULL

)

 

 

create table table_3 (

     `id` INT (11) NOT NULL,

    user_name varchar(20)

)

 

insert into table_2 values (4,"zhaoliu_2_1"),(2,"lisi_2_1"),(3,"wangmazi_2_1"),(1,"zhangsan_2"),(2,"lisi_2_2"),(4,"zhaoliu_2_2"),(3,"wangmazi_2_2")

 

insert into table_3 values (1,"zhaoliu_2_1"),(2, null)

 

-- 1、NOT IN子查询在有NULL值的情况下返回永远为空结果,查询容易出错

select user_name from table_2 where user_name not in (select user_name from table_3 where id!=1)

 

mysql root@10.48.186.32:t_test_zz5431> select user_name from table_2 where user_name not

                                    -> in (select user_name from table_3 where id!=1);

+-------------+

| user_name   |

|-------------|

+-------------+

rows in set

Time: 0.008s

mysql root@10.48.186.32:t_test_zz5431>

 

-- 2、单列索引不存null值,复合索引不存全为null的值,如果列允许为null,可能会得到“不符合预期”的结果集

-- 如果name允许为null,索引不存储null值,结果集中不会包含这些记录。所以,请使用not null约束以及默认值。

select from table_3 where name != 'zhaoliu_2_1'

 

-- 3、如果在两个字段进行拼接:比如题号+分数,首先要各字段进行非null判断,否则只要任意一个字段为空都会造成拼接的结果为null。

select CONCAT("1",nullfrom dual; -- 执行结果为null。

 

-- 4、如果有 Null column 存在的情况下,count(Null column)需要格外注意,null 值不会参与统计。

mysql root@10.48.186.32:t_test_zz5431> select from table_3;

+------+-------------+

|   id | user_name   |

|------+-------------|

|    1 | zhaoliu_2_1 |

|    2 | <null>      |

|   21 | zhaoliu_2_1 |

|   22 | <null>      |

+------+-------------+

rows in set

Time: 0.007s

mysql root@10.48.186.32:t_test_zz5431> select count(user_name) from table_3;

+--------------------+

|   count(user_name) |

|--------------------|

|                  2 |

+--------------------+

1 row in set

Time: 0.007s

 

-- 5、注意 Null 字段的判断方式, = null 将会得到错误的结果。

mysql root@localhost:cygwin> create index IDX_test on table_3 (user_name);

Query OK, 0 rows affected

Time: 0.040s

mysql root@localhost:cygwin>  select from table_3 where user_name is null\G

***************************[ 1. row ]***************************

id        | 2

user_name | None

 

1 row in set

Time: 0.002s

mysql root@localhost:cygwin> select from table_3 where user_name = null\G

 

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 的标志位

1

2

3

4

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语句

[3] 或许你不知道的10条SQL技巧

推荐↓↓↓

数据库开发

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值