Why is NULL not recommended for MySQL as column defaults?

Mondo Technology Updated on 2024-02-18

Today I'm going to share a high-frequency interview question that you can understand in 5 minutes."Why does MySQL not recommend using null as a column default?

The answer to this question is usually "".Columns with null values will invalidate the indexBut if you actually test it, you know that is null will use indexes, so the above statement has a loophole.

Those who are in a hurry pull to the bottom to see the conclusion.

Foreword

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.

The null value is a special constraint on a column, when we create a new column, if the data column is not explicitly declared with the keyword not null, MySQL will add a null constraint for us by default. Some developers are lazy to use MySQL's default recommended setting (i.e., allowing fields to use null values) when creating data tables. This bad habit can easily lead to uncertain query results and degrade database performance in scenarios where null is used.

Introduction

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 doesn't mean nothing, we need to pay attention to null and follow''(Null values) are two completely different values. There are three main types of null value operators that can be manipulated in MySQL.

is null

is not null

Spaceship operator, this operator is much like =, select null<=>null can return true, but select null=null returns false.

ifnull a function. How to use it to check it yourself......I would, anyway.

example

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

null will be obtained by comparing any operator to any other value, except for <=>.

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 represents an indeterminate value, and even if it is two nulls, they are not necessarily equal. (Like an uninitialized local variable in 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 |

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.

Any expression that has a return value that has null in it will get another null value.

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).

Using count(*) or count(null column) results differently, count(null column)<=count(*).

root@localhost mysql3306.sock)[zlm]>select count(*)count(name) from test_null;

count(*)count(name) |

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.

Although the result of select null=null is false, when we use distinct, group by, and order by, null is considered to be the same value.

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 supports indexing on columns with null values, but Oracle does not. This is what we usually call that if a column contains null, it will invalidate the index.

Strictly speaking, this statement is inaccurate for 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 | 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 | 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.

This is an example of my own testing.

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 | 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 | 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 | 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 | 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.

The use of null values in columns can easily lead to uncontrolled things happening and can sometimes severely slow down the performance of the system.

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

Perform statistical calculations on columns with null values, egcount(), max(), min(), and the results do not meet our expectations.

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

Interference sorting, grouping, deduplication results.

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

Sometimes we need to use ifnull() in SQL to ensure that the results are controllable in order to eliminate the technical debt that comes with null, but this complicates the program.

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

The null value is not stored in the original field space, but an additional byte is requested to annotate the field, and the field is added with a null constraint (just like an extra flag bit).

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.

Based on the above shortcomings, we do not recommend setting null as the default value for columns, you can use not null to eliminate the default setting, use 0 or''Empty strings instead of null.

Translator丨guangsu

*丨***j**aguide (id: j**aguide).

The DBAPLUS community welcomes contributions from technical personnel at editor@dbapluscn

Related Pages