MySQL为何不建议使用默认值为null列

通常能听到的答案是使用了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.

如果使用者对NULL属性不熟悉,很容易统计出错误的结果.

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.

参考资料

https://www.cnblogs.com/aaron8219/p/9259379.html

到此这篇关于MySQL为何不建议使用默认值为null列的文章就介绍到这了,更多相关MySQL默认值为null内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • MySQL中可为空的字段设置为NULL还是NOT NULL

    经常用mysql的人可能会遇到下面几种情况: 1.我字段类型是not null,为什么我可以插入空值 2.为什么not null的效率比null高 3.判断字段不为空的时候,到底要用 select * from table where column <> '' 还是要用 select * from table where column is not null 带着上面几个疑问,我们来简单的研究一下null 和 not null 到底有什么不一样,他们之间的区别是什么以及各自的效率问题. 首先,

  • mysql中is null语句的用法分享

    mysql数据库中is null语句的用法 注意在mysql中,0或 null意味着假而其它值意味着真.布尔运算的默认真值是1. 对null的特殊处理即是在前面的章节中,为了决定哪个动物不再是活着的,使用death is not null而不使用death != null的原因. 在group by中,两个null值视为相同. 执行order by时,如果运行 order by ... asc,则null值出现在最前面,若运行order by ... desc,则null值出现在最后面. nul

  • MySQL中对于NULL值的理解和使用教程

    NULL值的概念是造成SQL的新手的混淆的普遍原因,他们经常认为NULL是和一个空字符串''的一样的东西.不是这样的!例如,下列语句是完全不同的: mysql> INSERT INTO my_table (phone) VALUES (NULL); mysql> INSERT INTO my_table (phone) VALUES (""); 两个语句把值插入到phone列,但是第一个插入一个NULL值而第二个插入一个空字符串.第一个的含义可以认为是"电话号码不

  • MySQL查询空字段或非空字段(is null和not null)

    现在我们先来把test表中的一条记录的birth字段设置为空. mysql> update test set t_birth=null where t_id=1; Query OK, 1 row affected (0.02 sec) Rows matched: 1  Changed: 1  Warnings: 0 OK,执行成功! 设置一个字段值为空时的语法为:set <字段名>=NULL 说明一下,这里没有大小写的区分,可以是null,也可以是NULL. 下面看看结果: mysql&

  • mysql中将null值转换为0的语句

    复制代码 代码如下: SELECT IF(AVG(cai.conversionsRate) IS NULL,0,AVG(cai.conversionsRate)) AS conversionsRate FROM campaign_info cai WHERE insertTime BETWEEN '2011-02-01' AND '2011-02-04' AND googleCampaignId=23331401

  • mysql中替代null的IFNULL()与COALESCE()函数详解

    在MySQL中isnull()函数不能作为替代null值! 如下: 首先有个名字为business的表: SELECT ISNULL(business_name,'no business_name') AS bus_isnull FROM business WHERE id=2 直接运行就会报错: 错误代码: 1582 Incorrect parameter count in the call to native function 'isnull' 所以,isnull()函数在mysql中就行不

  • MySql中的IFNULL、NULLIF和ISNULL用法详解

    今天用到了MySql里的isnull才发现他和MSSQL里的还是有点区别,现在简单总结一下: mysql中isnull,ifnull,nullif的用法如下: isnull(expr) 的用法: 如expr 为null,那么isnull() 的返回值为 1,否则返回值为 0. mysql> select isnull(1+1); -> 0 mysql> select isnull(1/0); -> 1 使用= 的null 值对比通常是错误的. isnull() 函数同 is nul

  • mysql 转换NULL数据方法(必看)

    使用mysql查询数据库,当执行left join时,有些关联的字段内容是NULL,因此获取记录集后,需要对NULL的数据进行转换操作. 本文将提供一种方法,可以在查询时直接执行转换处理.使获取到的记录集不需要再进行转换. mysql提供了IFNULL函数 IFNULL(expr1, expr2) 如果expr1不是NULL,IFNULL()返回expr1,否则返回expr2 实例: user表结构和数据 +----+-----------+ | id | name | +----+------

  • MySQL为何不建议使用默认值为null列

    通常能听到的答案是使用了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 explicit

  • 解析MySQL设置当前时间为默认值的方法

    MySQL设置当前时间为默认值的问题我们经常会遇到,下面就为您介绍MySQL设置当前时间为默认值的实现全步骤,希望对您能有所启迪.数据库:test_db1创建表:test_ta1两个字段:id              (自增 且为主键),createtime 创建日期(默认值为当前时间) 方法一.是用alert table语句: 复制代码 代码如下: use test_db1; create table test_ta1( id mediumint(8) unsigned not nulll 

  • mysql中datetime类型设置默认值方法

    通过navicat客户端修改datetime默认值时,遇到了问题. 数据库表字段类型datetime,原来默认为NULL,当通过界面将默认值设置为当前时间时,提示"1067-Invalid default value for 'CREATE_TM'",而建表的时候,则不会出现这个问题,比如建表语句: CREATE TABLE `app_info1` ( `id` bigint(21) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID', `a

  • MySQL表字段时间设置默认值

    应用场景 在数据表中,要记录的每条数据是什么时候创建的,不需要应用程序去特意记录,而是由数据库获取当前时间自动记录创建时间. 在数据库中,要记录每条数据是什么时候修改的,不需要应用程序去特意记录,而由数据库获取当前时间自动记录修改时间. 在数据库中获取当前时间 oracle:select sysdate from dual; sqlserver:select getdate(); mysql:select sysdate();  select now(); MySQL中时间函数NOW()和SYS

  • MySQL如何修改字段的默认值和空值

    目录 MySQL修改字段的默认值和空值 修改字段默认值 修改字段值是否为空 MySQL默认值NULL.空值.Empty String的区别 如何选择? 先说结论 区别 MySQL修改字段的默认值和空值 修改字段默认值 修改: ALTER TABLE 表名 ALTER COLUMN 字段名 SET DEFAULT 默认值 删除: ALTER TABLE 表名 ALTER COLUMN 字段名 DROP DEFAULT 修改字段值是否为空 设为空: ALTER TABLE 表名 MODIFY 字段名

  • 详解Mysql数据库date, datetime类型设置0000-00-00默认值(default)报错问题

    现象:MySQL5.7版本之后,date, datetime类型设置默认值"0000-00-00",出现异常:Invalid default value for 'time' 原因:在命令行窗口查看当前的sql_mode配置: select @@sql_mode; 结果如下: ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE,  ERROR_FOR_DIVISION_BY_ZERO, NO_AU

  • MySQL 如何处理隐式默认值

    有同学说遇到了主从不一致的问题. 大概情况是,从库是用mysqldump导出导入数据的方式创建的.创建成功后,在用mysqldump验证主从的表结构是否一致的时候,发现有些表定义不一致: 从他的比较结果可以看到,在从库端,有三个列的定义中被加入了"default null". 怀疑环境被人人为修改过,但是最终确认环境没有被动过.然后又做了一边测试,使用mysqldump导出数据,使用source将数据导入从库后,发现还是有这个现象,问是不是source命令有bug! 其实,这个跟MyS

  • C#不同类型的成员变量(字段)的默认值介绍

    创建类的一个实例时,在执行构造函数之前,如果你没有给成员变量赋初始值,C#编译器缺省将每一个成员变量初始化为他的默认值. 如果变量是方法的局部变量,编译器就会认为在使用该变量之前,代码必须给它显示的设定一个值.否则会发生"使用了未赋值的局部变量"的错误. 对于其他情况,编译器会在创建变量时,把变量初始化为默认值.1.对于整型.浮点型.枚举类型(数值型),默认值为0或0.0.2.字符类型的默认值为\x0000.3.布尔类型的默认值为false.4.引用类型的默认值为null. 如果声时变

  • django 模型字段设置默认值代码

    我就废话不多说了,大家还是直接看代码吧~ class SitService(models.Model): applicationname = models.CharField(max_length=50,primary_key=True) ip = models.CharField(max_length=50) port = models.IntegerField(default=22) #设置默认值为22 path = models.CharField(max_length=50) 补充知识:

  • Django model.py表单设置默认值允许为空的操作

    blank=True 默认值为blank=Flase,表示默认不允许为空, blank=True admin级别可以为空 null=True 默认值为null=Flase,表示默认不允许为空 null=True 数据库级别可以为空 补充知识:Django中models.py字段选项null和blank的区别和使用 1.null 如果null=True,数据库中空值储存为NULL,默认为False. 2.blank 如果blank=True,则允许字段为空.默认为False. 需要注意的是,这不同

随机推荐