当前位置:网站首页>Reasons why null is not recommended for MySQL fields
Reasons why null is not recommended for MySQL fields
2022-07-28 07:23:00 【georgesnoopy】
MySQL A thousand no Null The reason of
null It seems to be a headache everywhere , such as Java It's a headache NullPointerException, To avoid the unexpected null pointer exception , For thousands of years, programmers have had to be careful in their code if Judge , Cumbersome and bloated , So java8 Introduced Optional To avoid this problem .
What we're going to talk about next is MySQL Inside null, In a large number of MySQL Optimization articles and books have mentioned that fields should be used as much as possible NOT NULL, instead of NULL, Except in special circumstances . But they only give the conclusion, not explain the reason .
commonly , Many fields use null The reasons can be summarized as the following three ;
- NULL Is the default when creating a data table , Novice or uninformed or troublesome programmers won't notice this .
- A lot of people think not null More space is needed , It's not the point .
- The point is that many programmers feel NULL In development, you don't have to judge whether to insert data , Write sql It's more convenient and quick to use the sentence .
Mysql Official documents for null A description of the field .
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.
《 High performance mysql The second edition 》 It is also mentioned in ,Mysql It's hard to optimize the reference nullable column query , It makes the index 、 Index statistics and values are more complex . Nullable columns need more storage space , It also needs to be mysql Special treatment inside . After the nullable column is indexed , Each record requires an extra byte , It can also lead to MYISAM The fixed size index in becomes the variable size index .
in other words , Not recommended. It can be null The field of is well founded , It's not out of nowhere .
null Change the column to non null Columns can cause pages to split
NULL Value to non NULL Can't update in place , More prone to index fragmentation , Which affects performance .
Mysql The storage units of data are stored in columns , The organization of the index is also sorted from small to large .

If page2 The column in used to be null, Just in page2 put down , But when changing this column to non null after ,page2 I can't put it down , Then it will lead to page2 Division . If this time page3 It's good to have space , If everything in the future page There's no room , Then it will cause all the following page Will split , Update performance is affected .
But notice : But put NULL Column to NOT NULL The performance implications are small , Unless you're sure it's causing problems , Otherwise, don't make it a priority optimization measure , The most important thing is the appropriateness of the type of column used .
timestamp The columns of type are null Go wrong
NULL Values in timestamp It's easy to have problems under the type , In particular, no parameters are enabled explicit_defaults_for_timestamp
The query criteria include null Columns need special attention , It's easy to make mistakes
mysql in , Any value sum null Comparison , All back to null, instead of true perhaps false.

Include null=null The result is null, No true

So once the query conditions are used null, Instead of using is null perhaps is not null There will be mistakes . No value will be returned .
table3 The data in the table are as follows :

as follows 4 strip sql Statement does not return an empty set :

The reason is mysql in , Any value sum null After comparison, they are null, instead of true perhaps false, All for fields are null Of , Will not return .
alike , The operation of greater than less than equal sign is the same .

select * from table1 where age>-1.age=null The line of will not return .

But for in In the list of null Of , If it's OK, the effect is equivalent to ignoring null

If it's just these simple statements , May know mysql in null Compared with any value, it is null This rule , In fact, it can be avoided , But I'm afraid the conditions are dynamic , If there are sub queries :
![]()
So if table1 and table2 Of user_name All allowed null, This sql It can't be found table2 in user_name by null Those records .
Empathy

Return the result , Will not contain user_name=null The record of . Be careful , If user_name There is no index on , So it's actually because ’aaa’=null return null, So I won't get it back user_name=null The line of , But even user_name There's an index on , that On the secondary index tree , The field will not be saved as null( Think about if you save , Can't compare sizes ), So I won't get it back user_name=null The line of
summary :
because mysql in ,null Value and any value , Will return to null, The resulting conditions include null When , The return result may be different from what you think .
Some function input parameters have null When , The return value is null
contact() Method , If there are null, Return is null

Null Columns need more storage : An extra byte is needed to determine whether it is NULL The mark of a


table1 and table3 It's exactly the same , The only difference is user_name Field ,table1 yes not null, and table3 Of user_name No, not null Constraints .
Explain Output key_len There are three factors that have to do with it : data type 、 Character encoding 、 Is it NULL.
Utf8mb4 Encoding is 4 byte ,utf8 yes 3 byte
- not null Field of
key_len= The number of bytes occupied by the index field +2 Byte variable length field length ( Fixed length type does not need )
Such as code set =utf8mb6 Of varchar(20),ken_len=82
62=20*4 +2
- Allow for null Field
key_len= The number of bytes occupied by the index field +2 Byte variable length field length ( Fixed length type does not need )+1( Whether the storage is null The logo of )
Such as code set =utf8mb6 Of varchar(20),ken_len=83
83=20*4+2+1
Therefore, it is better not to use the index field as NULL, because NULL Will make the index 、 Index statistics and values are more complex , And it needs an extra byte of storage space . Based on the above reasons and reasons , I don't think we need to Null The reason should be enough
Solution
have access to nullable value replace . such nullable value The design of is very common , Even some storage is not supported null Of , such as ES, So if you want to express this way , Is to adopt nullable value Instead of (ES Official documents ).
So-called nullable value It is a value that has no business meaning for this field . such as age Field , You can use any less than or equal to 0 The value of nullable value, Age is definitely impossible to be less than or equal to 0 Of . You need to pay attention to this way , When showing the front end , To filter out nullable value, Otherwise, show your age =0, This is to make users look confused
remarks : This article reprints the following article , However, some modifications and additions have been made .
original text :https://www.techug.com/post/you-should-not-use-null-in-mysql.html
边栏推荐
- GFS分布式文件系统
- Serial port configuration of raspberry pie
- Student duty problems
- GFS distributed file system
- Review of C language (variable parameters)
- 一口气学完4种 Redis 集群方案,真是各有千秋
- Easypoi export table with echars chart
- Gobang optimized version
- Basic usage and precautions of arrow function (= >) and three-point operator (...) in ES6 (this points to)
- object detection
猜你喜欢

最短寻道时间优先(SSTF)

删除链表中的节点——每日一题

Soft exam certificate can be used like this! Get a certificate = get a professional title?

MySQL queries all descendant nodes under the parent node. When querying the user list, it is processed by multi-level (company) departments. According to reflection, it recurses the tree structure too

低端电脑如何深度学习秘籍-使用mistGPU计算平台

Reptile learning summary

GFS distributed file system

Pytorch - storage and loading model

VLAN configuration

Easypoi one to many, merge cells, and adapt the row height according to the content
随机推荐
Use of C3d
Date n days ago
Principle and configuration of redis master-slave replication
nodejs操作MongoDB
Map uses tuple to realize multiple value values
Joern's code uses -devign
浅谈深分页问题
Basic usage and precautions of arrow function (= >) and three-point operator (...) in ES6 (this points to)
Rsync+inotify to realize remote real-time synchronization
guava之EventBus
Nrf51822 review summary
Serial port configuration of raspberry pie
OJ questions about fast and slow pointers in linked lists
C language: understand the creation and destruction of function stack frames through an example
Shell -- first day homework
RAID disk array
教程篇(7.0) 06. 零信任网络访问ZTNA * FortiClient EMS * Fortinet 网络安全专家 NSE 5
Install Nessus under win
LeNet5、AlexNet、VGGNet、ResNet
隔离级别RR、间隙锁、幻读