译者:guangsu.

blog.csdn.net/qq_30549099/article/details/107395521

通常能听到的答案是使用了NULL值的列将会使索引失效,但是如果实际测试过一下,你就知道IS NULL会使用索引.所以上述说法有漏洞.

着急的人拉到最下边看结论

Preface

Null is a special constraint of columns.
The columns in table will be added null constrain if you do not define the column with “not null” key words explicitly
when creating the table.Many programmers like to define columns by default
because of the conveniences(reducing the judgement code of nullibility) what consequently
cause some uncertainty of query and poor performance of database.

NULL值是一种对列的特殊约束,我们创建一个新列时,如果没有明确的使用关键字not null声明该数据列,Mysql会默认的为我们添加上NULL约束.
有些开发人员在创建数据表时,由于懒惰直接使用Mysql的默认推荐设置.(即允许字段使用NULL值).而这一陋习很容易在使用NULL的场景中得出不确定的查询结果以及引起数据库性能的下降.

Introduce

Null is null means it is not anything at all,we cannot think of null is equal to ‘’ and they are totally different.
MySQL provides three operators to handle null value:“IS NULL”,“IS NOT NULL”,"<=>" and a function ifnull().
IS NULL: It returns true,if the column value is null.
IS NOT NULL: It returns true,if the columns value is not null.
<=>: It’s a compare operator similar with “=” but not the same.It returns true even for the two null values.
(eg. null <=> null is legal)
IFNULL(): Specify two input parameters,if the first is null value then returns the second one.
It’s similar with Oracle’s NVL() function.

NULL并不意味着什么都没有,我们要注意 NULL 跟 ''(空值)是两个完全不一样的值.MySQL中可以操作NULL值操作符主要有三个.

  • IS NULL

  • IS NOT NULL

  • <=> 太空船操作符,这个操作符很像=,select NULL<=>NULL可以返回true,但是select NULL=NULL返回false.

  • IFNULL 一个函数.怎么使用自己查吧…反正我会了

Example

Null never returns true when comparing with any other values except null with “<=>”.

NULL通过任一操作符与其它值比较都会得到NULL,除了<=>.

(root@localhost mysql3306.sock)[zlm]>create table test_null(-> id int not null,-> name varchar(10)-> );
Query OK, 0 rows affected (0.02 sec)(root@localhost mysql3306.sock)[zlm]>insert into test_null values(1,'zlm');
Query OK, 1 row affected (0.00 sec)(root@localhost mysql3306.sock)[zlm]>insert into test_null values(2,null);
Query OK, 1 row affected (0.00 sec)(root@localhost mysql3306.sock)[zlm]>select * from test_null;
+----+------+
| id | name |
+----+------+
|  1 | zlm  |
|  2 | NULL |
+----+------+
2 rows in set (0.00 sec)(root@localhost mysql3306.sock)[zlm]>select * from test_null where name=null;
Empty set (0.00 sec)(root@localhost mysql3306.sock)[zlm]>select * from test_null where name is null;
+----+------+
| id | name |
+----+------+
|  2 | NULL |
+----+------+
1 row in set (0.00 sec)(root@localhost mysql3306.sock)[zlm]>select * from test_null where name is not null;
+----+------+
| id | name |
+----+------+
|  1 | zlm  |
+----+------+
1 row in set (0.00 sec)(root@localhost mysql3306.sock)[zlm]>select * from test_null where null=null;
Empty set (0.00 sec)(root@localhost mysql3306.sock)[zlm]>select * from test_null where null<>null;
Empty set (0.00 sec)(root@localhost mysql3306.sock)[zlm]>select * from test_null where null<=>null;
+----+------+
| id | name |
+----+------+
|  1 | zlm  |
|  2 | NULL |
+----+------+
2 rows in set (0.00 sec)//null<=>null always return true,it's equal to "where 1=1".

Null means “a missing and unknown value”.Let’s see details below.

NULL代表一个不确定的值,就算是两个NULL,它俩也不一定相等.(像不像C中未初始化的局部变量)

(root@localhost mysql3306.sock)[zlm]>SELECT 0 IS NULL, 0 IS NOT NULL, '' IS NULL, '' IS NOT NULL;
+-----------+---------------+------------+----------------+
| 0 IS NULL | 0 IS NOT NULL | '' IS NULL | '' IS NOT NULL |
+-----------+---------------+------------+----------------+
|         0 |             1 |          0 |              1 |
+-----------+---------------+------------+----------------+
1 row in set (0.00 sec)//It's not equal to zero number or vacant string.
//In MySQL,0 means fasle,1 means true.(root@localhost mysql3306.sock)[zlm]>SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL;
+----------+-----------+----------+----------+
| 1 = NULL | 1 <> NULL | 1 < NULL | 1 > NULL |
+----------+-----------+----------+----------+
|     NULL |      NULL |     NULL |     NULL |
+----------+-----------+----------+----------+
1 row in set (0.00 sec)//It cannot be compared with number.
//In MySQL,null means false,too.

It truns null as a result if any expression contains null value.

任何有返回值的表达式中有NULL参与时,都会得到另外一个NULL值.

(root@localhost mysql3306.sock)[zlm]>select ifnull(null,'First is null'),ifnull(null+10,'First is null'),ifnull(concat('abc',null),'First is null');
+------------------------------+---------------------------------+--------------------------------------------+
| ifnull(null,'First is null') | ifnull(null+10,'First is null') | ifnull(concat('abc',null),'First is null') |
+------------------------------+---------------------------------+--------------------------------------------+
| First is null                | First is null                   | First is null                              |
+------------------------------+---------------------------------+--------------------------------------------+
1 row in set (0.00 sec)//null value needs to be disposed with ifnull() function,what usually causes sql statement more complex.
//As we all know,MySQL does not support funcion index.Therefore,indexes on the column may not be used.That's really worse.

It’s diffrent when using count(*) & count(null column).

使用count(*) 或者 count(null column)结果不同,count(null column)<=count(*).

(root@localhost mysql3306.sock)[zlm]>select count(*),count(name) from test_null;
+----------+-------------+
| count(*) | count(name) |
+----------+-------------+
|        2 |           1 |
+----------+-------------+
1 row in set (0.00 sec)//count(*) returns all rows ignore the null while count(name) returns the non-null rows in column "name".
//This will also leads to uncertainty if someone is unaware of the details above.

When using distinct,group by,order by,all null values are considered as the same value.

虽然select NULL=NULL的结果为false,但是在我们使用distinct,group by,order by时,NULL又被认为是相同.

(root@localhost mysql3306.sock)[zlm]>insert into test_null values(3,null);
Query OK, 1 row affected (0.00 sec)(root@localhost mysql3306.sock)[zlm]>select distinct name from test_null;
+------+
| name |
+------+
| zlm  |
| NULL |
+------+
2 rows in set (0.00 sec)//Two rows of null value returned one and the result became two.(root@localhost mysql3306.sock)[zlm]>select name from test_null group by name;
+------+
| name |
+------+
| NULL |
| zlm  |
+------+
2 rows in set (0.00 sec)//Two rows of null value were put into the same group.
//By default,group by will also sort the result(null row showed first).(root@localhost mysql3306.sock)[zlm]>select id,name from test_null order by name;
+----+------+
| id | name |
+----+------+
|  2 | NULL |
|  3 | NULL |
|  1 | zlm  |
+----+------+
3 rows in set (0.00 sec)//Three rows were sorted(two null rows showed first).

MySQL supports to use index on column which contains null value(what’s different from oracle).

MySQL中支持在含有NULL值的列上使用索引,但是Oracle不支持.这就是我们平时所说的如果列上含有NULL那么将会使索引失效.

严格来说,这句话对与MySQL来说是不准确的.

(root@localhost mysql3306.sock)[sysbench]>show tables;
+--------------------+
| Tables_in_sysbench |
+--------------------+
| sbtest1            |
| sbtest10           |
| sbtest2            |
| sbtest3            |
| sbtest4            |
| sbtest5            |
| sbtest6            |
| sbtest7            |
| sbtest8            |
| sbtest9            |
+--------------------+
10 rows in set (0.00 sec)(root@localhost mysql3306.sock)[sysbench]>show create table sbtest1\G
*************************** 1. row ***************************Table: sbtest1
Create Table: CREATE TABLE `sbtest1` (`id` int(11) NOT NULL AUTO_INCREMENT,`k` int(11) NOT NULL DEFAULT '0',`c` char(120) NOT NULL DEFAULT '',`pad` char(60) NOT NULL DEFAULT '',PRIMARY KEY (`id`),KEY `k_1` (`k`)
) ENGINE=InnoDB AUTO_INCREMENT=100001 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)(root@localhost mysql3306.sock)[sysbench]>alter table sbtest1 modify k int null,modify c char(120) null,modify pad char(60) null;
Query OK, 0 rows affected (4.14 sec)
Records: 0  Duplicates: 0  Warnings: 0(root@localhost mysql3306.sock)[sysbench]>insert into sbtest1 values(100001,null,null,null);
Query OK, 1 row affected (0.00 sec)(root@localhost mysql3306.sock)[sysbench]>explain select id,k from sbtest1 where id=100001;
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
| id | select_type | table   | partitions | type  | possible_keys | key     | key_len | ref   | rows | filtered | Extra |
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | sbtest1 | NULL       | const | PRIMARY       | PRIMARY | 4       | const |    1 |   100.00 | NULL  |
+----+-------------+---------+------------+-------+---------------+---------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)(root@localhost mysql3306.sock)[sysbench]>explain select id,k from sbtest1 where k is null;
+----+-------------+---------+------------+------+---------------+------+---------+-------+------+----------+--------------------------+
| id | select_type | table   | partitions | type | possible_keys | key  | key_len | ref   | rows | filtered | Extra                    |
+----+-------------+---------+------------+------+---------------+------+---------+-------+------+----------+--------------------------+
|  1 | SIMPLE      | sbtest1 | NULL       | ref  | k_1           | k_1  | 5       | const |    1 |   100.00 | Using where; Using index |
+----+-------------+---------+------------+------+---------------+------+---------+-------+------+----------+--------------------------+
1 row in set, 1 warning (0.00 sec)//In the first query,the newly added row is retrieved by primary key.
//In the second query,the newly added row is retrieved by secondary key "k_1"
//It has been proved that indexes can be used on the columns which contain null value.
//column "k" is int datatype which occupies 4 bytes,but the value of "key_len" turn out to be 5.what's happed?Because null value needs 1 byte to store the null flag in the rows.

这个是我自己测试的例子.

mysql> select * from test_1;
+-----------+------+------+
| name      | code | id   |
+-----------+------+------+
| gaoyi     | wo   |    1 |
| gaoyi     | w    |    2 |
| chuzhong  | wo   |    3 |
| chuzhong  | w    |    4 |
| xiaoxue   | dd   |    5 |
| xiaoxue   | dfdf |    6 |
| sujianhui | su   |   99 |
| sujianhui | NULL |   99 |
+-----------+------+------+
8 rows in set (0.00 sec)mysql> explain select * from test_1 where code is NULL;
+----+-------------+--------+------------+------+---------------+------------+---------+-------+------+----------+-----------------------+
| id | select_type | table  | partitions | type | possible_keys | key        | key_len | ref   | rows | filtered | Extra                 |
+----+-------------+--------+------------+------+---------------+------------+---------+-------+------+----------+-----------------------+
|  1 | SIMPLE      | test_1 | NULL       | ref  | index_code    | index_code | 161     | const |    1 |   100.00 | Using index condition |
+----+-------------+--------+------------+------+---------------+------------+---------+-------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)mysql> explain select * from test_1 where code is not NULL;
+----+-------------+--------+------------+-------+---------------+------------+---------+------+------+----------+-----------------------+
| id | select_type | table  | partitions | type  | possible_keys | key        | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+--------+------------+-------+---------------+------------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | test_1 | NULL       | range | index_code    | index_code | 161     | NULL |    7 |   100.00 | Using index condition |
+----+-------------+--------+------------+-------+---------------+------------+---------+------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)mysql> explain select * from test_1 where code='dd';
+----+-------------+--------+------------+------+---------------+------------+---------+-------+------+----------+-----------------------+
| id | select_type | table  | partitions | type | possible_keys | key        | key_len | ref   | rows | filtered | Extra                 |
+----+-------------+--------+------------+------+---------------+------------+---------+-------+------+----------+-----------------------+
|  1 | SIMPLE      | test_1 | NULL       | ref  | index_code    | index_code | 161     | const |    1 |   100.00 | Using index condition |
+----+-------------+--------+------------+------+---------------+------------+---------+-------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)mysql> explain select * from test_1 where code like "dd%";
+----+-------------+--------+------------+-------+---------------+------------+---------+------+------+----------+-----------------------+
| id | select_type | table  | partitions | type  | possible_keys | key        | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+--------+------------+-------+---------------+------------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | test_1 | NULL       | range | index_code    | index_code | 161     | NULL |    1 |   100.00 | Using index condition |
+----+-------------+--------+------------+-------+---------------+------------+---------+------+------+----------+-----------------------+
1 row in set, 1 warning (0.00 sec)

Summary 总结

null value always leads to many uncertainties when disposing sql statement.It may cause bad performance accidentally.

列中使用NULL值容易引发不受控制的事情发生,有时候还会严重托慢系统的性能.

例如:

null value will not be estimated in aggregate function() which may cause inaccurate results.

对含有NULL值的列进行统计计算,eg. count(),max(),min(),结果并不符合我们的期望值.

null value will influence the behavior of the operations such as “distinct”,“group by”,“order by” which causes wrong sort.

干扰排序,分组,去重结果.

null value needs ifnull() function to do judgement which makes the program code more complex.

有的时候为了消除NULL带来的技术债务,我们需要在SQL中使用IFNULL()来确保结果可控,但是这使程序变得复杂.

null value needs a extra 1 byte to store the null information in the rows.

NULL值并是占用原有的字段空间存储,而是额外申请一个字节去标注,这个字段添加了NULL约束.(就像额外的标志位一样)

As these above drawbacks,it’s not recommended to define columns with default null.
We recommand to define “not null” on all columns and use zero number & vacant string to substitute relevant data type of null.

根据以上缺点,我们并不推荐在列中设置NULL作为列的默认值,你可以使用NOT NULL消除默认设置,使用0或者''空字符串来代替NULL.

END

推荐好文

强大,10k+点赞的 SpringBoot 后台管理系统竟然出了详细教程!分享一套基于SpringBoot和Vue的企业级中后台开源项目,代码很规范!
能挣钱的,开源 SpringBoot 商城系统,功能超全,超漂亮!

为什么MySQL不建议使用NULL作为列默认值?相关推荐

  1. 数据库查询新增一列默认值

    数据库查询新增一列默认值 场景:我们在做数据库查询时候,可能会遇到需要需要返回一列默认值. 假如我们在查询一张user表时,需要返回一列固定的比如机构号org,我们可以通过sql语句实现. selec ...

  2. oracle创建列默认值,表列添加默认值的方法

    在修改表结构时,有时候会涉及到添加默认值. 下面是在11.2.0.3版本数据库中进行测试的结果: Connected to Oracle Database 11g Enterprise Edition ...

  3. mysql unique 重复_Mysql中 unique列插入重复值该怎么解决呢

    当unique列在一个UNIQUE键上插入包含重复值的记录时,我们可以控制MySQL如何处理这种情况:使用IGNORE关键字或者ON DUPLICATE KEY UPDATE子句跳过INSERT.中断 ...

  4. mysql中教如何拼接字段(列)值、加入运算、设置别名(非常实用)

    https://blog.csdn.net/hanhanwanghaha宝藏女孩 欢迎您的关注! 欢迎关注微信公众号:宝藏女孩的成长日记 如有转载,请注明出处(如不注明,盗者必究)   在mysql中 ...

  5. mysql修改表中某个字段的默认值

    Mysql中用SQL增加.删除字段,修改字段名.字段类型.注释,调整字段顺序总结 在网站重构中,通常会进行数据结构的修改,所以添加,删除,增加mysql表的字段是难免的,有时为了方便,还会增加修改表或 ...

  6. mysql为datetime类型的字段设置默认值current_timestamp,引发 Invalid default value for 错误...

    [起因] 在本地数据库执行测试平台数据库结构文件data_struct.sql,执行建表语句类似如下: CREATE TABLE `demo` (`id` int(10) unsigned NOT N ...

  7. mysql创建数据库没有默认值报错_详解Mysql数据库date, datetime类型设置0000-00-00默认值(default)报错问题...

    现象:MySQL5.7版本之后,date, datetime类型设置默认值"0000-00-00",出现异常:Invalid default value for 'time' 原因 ...

  8. oracle sql列默认值,sql – Oracle:指定对象类型列的默认值

    我有一个带有no-args构造函数的对象类型,但是当我将它指定为该类型列的默认值时,我得到ORA-00904:无效的标识符错误. 例: CREATE OR REPLACE TYPE test_t AS ...

  9. oracle中如果值为空null则取默认值0,nvl函数

    在oracle中如果某个字段有空值,在和其他字段相加的时候会使得结果也为空,这个时候需要令null默认变为0(或其他指定的数值 select nvl(S_PLEDGE_SHARES,0) + nvl( ...

最新文章

  1. 32位jdk_MyEclipse 10((32/64位)、(MAC)、(Linux))软件安装教程
  2. 【亲测有效】如何在win10上激活Burp Suite,如何注册激活Burp Suite,破解Burp Suite的详细步骤
  3. 「后端小伙伴来学前端了」Vue中全局事件总线(GlobalEventBus)原理及探究过程
  4. java 三维数组长方体求体积_已知任意一个四面体的六条棱长,如何求出其体积?...
  5. C语言基础MessageBox(......)用法详解
  6. 病毒行为分析初探(三)
  7. 计算机发展史的十大成就,2019中国十大科技成就:数个“第一”创造历史
  8. 计算机lab模式适用于,计算机考证二级选择题1
  9. Python-Learn
  10. 基于JAVA+SpringBoot+Mybatis+MYSQL的旅游网站系统
  11. WARNING:Result from SERVER not valid. Partial Result:
  12. Java语言程序设计(一)选择题
  13. 苹果开发者账户需要同意并添加电话号码,苹果账号忘记验证问题解决方案
  14. 洛谷—— P1268 树的重量
  15. Appium下载遇到的问题
  16. easytrader 量化交易平台连接同花顺软件使用平安证券
  17. Java中常见的几种数组排序方法
  18. THINKPAD SL400 重装XP系统的经历
  19. 保镖机器人作文_【保镖的作文】_玛雅作文网
  20. CTFShow“萌心区”WP(上)

热门文章

  1. 谁说格力不做手机了?格力折叠屏手机了解一下
  2. 尴尬了!“中国版ins”绿洲 logo涉嫌抄袭,确认已下架
  3. 三星旗舰Galaxy Note 10系列发布 5G版本国行尝鲜价8299元
  4. 苹果新机发布在即 供应链齐泼冷水:卖不了7000万台
  5. 任达华遇袭是效仿“宏颜获水”事件?百度回应:严惩肇事者 以儆效尤
  6. 超5000元!骁龙660新机发布:限量供应价格感人
  7. jrtplib的编译方法
  8. 安装mysql 5.7.19 winx64解压缩版
  9. react生命周期(自己的方式理解)
  10. 学生签到系统c代码_C++实现学生考勤信息管理系统