(Transfer) The difference between NULL and empty value in MySQL

The difference between NULL and null value in MySQLhttp

: //www.ywnds.com/?p=

10295Partners who have studied relational databases know that NULL refers to an uncertain value, which is definitely a nightmare in the database; and Null value, generally for string types, refers to a string type without any value, and a variable of character type is set to a null value: set @vs=”, a null value is different from no value. Some people may ask, no value What is it? No value means that there is no data in the data table. No value and indeterminate value, from a literal point of view, the definition between the two is very clear. It's very confusing.

The difference between NULL values ​​and null values ​​in MySQL, notice that NULL values ​​are unknown, occupy space, and do not go into the index. I believe that many people who have used MySQL for a long time have no idea about the properties of these two fields. The concept is not very clear, and there are generally the following questions:

1. My field type is not null, why can I insert a null value?

2. Why is not null more efficient than null?

3. When judging that the field is not null, in the end To select * from table where column <> "or use select * from table where column is not null?

With the above questions in mind, let's delve into the difference between null and not null.

First of all, we have to figure out the concepts of "null value" and "NULL":

1. A null value does not occupy space.

2. NULL in MySQL actually takes up space. The following is the official explanation from MYSQL

"NULL columns require additional space in the row to record whether their values ​​are NULL. For MyISAM tables, each NULL column takes one bit extra, rounded up to the nearest byte."

For example, you have a cup, NULL It means that the cup is empty, and NULL means that the cup is full of air. Although the cups seem to be empty, the difference is very big.

After understanding the concepts of "null value" and "NULL", the problem is basically clear, let's test it with an example:


CREATE TABLE `test` (
`col1` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`col2 ` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL
) ENGINE = INNODB;

CREATE TABLE `test` (
`col1` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL ,
`col2` VARCHAR( 10 ) CHARACTER SET utf8 COLLATE utf8_general_general
) ENGINE = INNODB;
insert data:


mysql> INSERT INTO `test` VALUES (NULL,1);
ERROR 1048 (23000): Column 'col1' cannot be null
1
2
mysql> INSERT INTO `test` VALUES (NULL,1);
ERROR 1048 (23000): Column 'col1' cannot be null
MySQL发生错误,再来一条:


mysql> INSERT INTO `test` VALUES ('NULL',1);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO `test` VALUES ('',1);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO `test` VALUES ('NULL',1);
Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO `test` VALUES ('',1);
Query OK, 1 row affected (0.01 sec)
成功插入。

It can be seen that the field of NOT NULL cannot insert "NULL", only "null value" or a value can be inserted, and the above question 1 has the answer. In addition, I am here 'NULL' is equivalent to a string, not a NULL value, such as IS NULL can not be found.


mysql> select * from test1 where col1 is null;
Empty set (0.00 sec)
1
2
mysql> select * from test1 where col1 is null;
Empty set (0.00 sec)
and equal to 'NULL' can query:


mysql> select * from test1 where col1='null';
+------+------+
| col1 | col2 |
+------+------+
| NULL | 1 |
+-- ----+------+
1 row in set (0.00 sec)

mysql> select * from test1 where col1='null';
+------+------+
| col1 | col2 |
+------+------+
| NULL | 1 |
+------+------+
1 row in set (0.00 sec)
For question 2, as we have already said above, NULL is not actually a null value, but takes up space, so when MySQL compares, NULL will participate in the field comparison, so it is more efficient. part of the impact.

Moreover, NULL values ​​are not stored when indexing the table, so if the indexed field can be NULL, the efficiency of the index will drop a lot.

Let's insert a few more pieces of data into the test table:


mysql> INSERT INTO `test` VALUES ('', NULL);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO `test` VALUES ('1', '2');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO `test` VALUES ('', NULL);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO `test` VALUES (' 1', '2');
Query OK, 1 row affected (0.00 sec)
Now the data in the table:

Now according to the requirements, I want to count all the data in the test table that col1 is not empty, I should use "<> "" Or "IS NOT NULL", let's see the difference in results.


mysql>
Empty set (0.00 sec)

mysql> select * from test1 where col2 is null;
+------+------+
| col1 | col2 |
+------+------+
|      | NULL |
+------+------+
1 row in set (0.00 sec)

mysql> select * from test1 where col1 is null;
Empty set (0.00 sec)

mysql> select * from test1 where col2 is null;
+------+------+
| col1 | col2 |
+------+------+
|      | NULL |
+------+------+
1 row in set (0.00 sec)

mysql> select * from test1 where col1 <> '';
+------+------+
| col1 | col2 |
+------+------+
| NULL | 1    |
| 1    | 2    |
+------+------+
2 rows in set (0.00 sec)

mysql> select * from test1 where col1 <> '';
+------+------ +
| col1 | col2 |
+------+------+
| NULL | 1 |
| 1 | 2 |
+------+------+
2 rows in set (0.00 sec)
As you can see, the results are quite different, so we must find out which search criteria to use according to business needs.

--------------------------------------------->

MySQL database is an open source database based on structured data, and SQL statement is the core language in MySQL database. However, there are two pitfalls to be aware of when executing SQL statements in a MySQL database.

Trap 1: Empty value is not necessarily empty

Null value is a special field. In the MySQL database, in different situations, null values ​​often represent different meanings. This is a feature of MySQL databases. For example, in ordinary fields (character data), a null value means a null value. But if you insert a null value into a TimesTamp type field, the null value is not necessarily null. What happened at this time?

I created a table first. There are two fields in this table: User_id (its data type is int), Date (its data type is TimesTamp). Now insert a record into this table, which inserts a NULL null value into the Date field. But when we query, the result shows the current time of the inserted record. What's going on here? In fact, this is a pitfall that is often encountered when executing SQL statements in a MySQL database: null values ​​are not necessarily null. During operation, it is clear that a null value is inserted, but the final query is not a null value.

In the MySQL database, NULL represents a special meaning for some special types of columns, not just a null value. For these special types of columns, there are two main things to keep in mind. One is the TimesTamp data type mentioned above by the author. If a Null value is inserted into a column of this data type, it represents the current time of the system. The other is a column with the auto_increment attribute. If you insert a Null value into the column of this attribute, the system will insert a sequence of positive integers. And if Null data is inserted into a column of other data types, such as character data, it will insert a null value.

Trap 2: Null is not necessarily equal to the null character

In MySQL, is the null value (Null) the same as the null character ('')? the answer is negative.

In the same database table, insert a Null value data and a '' null character data at the same time, and then use the Select statement to query. Obviously the results shown are not the same. As you can see from this result, the null value is not equal to the null character. This is the second pitfall encountered in executing SQL statements in MySQL. In practical work, null data and null characters often have different meanings. Database administrators can choose according to actual needs. For example, for fields such as phone numbers, it can be set to a null value by default (indicating that the phone number of the other party is not known at all) or a null character (indicating that the number is later cancelled) and so on. Since they have different representations in the database, database administrators need to treat them differently. I prefer to use null values ​​rather than null characters. This is mainly because there are several special operation characters for the null value data type. If a field is a null character, the database uses the field name instead. Conversely, if a null value is inserted, NULL is displayed directly. This is also different from how other databases are displayed.

IS NULL and IS NOT NULL keywords. If you want to determine whether a field contains data with null values, you need to use a special keyword. The former indicates that the field is empty, and the latter indicates that the field is not empty. These two keywords are very useful in the query conditions of the Select statement. If you need to query all users whose phone numbers are empty (they need to add phone number information), you can add the keyword is not null to the query conditions. To judge NULL, use is null or is not null, and the ifnull function can be used in the SQL statement. To judge the empty string '', use =” or <>”, and if (col, col, 0) can be used in the SQL statement, that is: when col is true (non-null, and non-”) display, otherwise print 0.

In general, except for count(0) and count(*), aggregate functions ignore NULL values ​​and count non-NULL values. In addition, an empty table will also produce aggregated values ​​that result in NULL. When aggregate column values ​​are all NULL values, since aggregate functions ignore NULL values, when computing aggregate values ​​for aggregate functions (max, min, avg, and sum), the database engine cannot determine these aggregate functions because there are no values ​​to aggregate The return value, therefore, the database engine returns a NULL value.


mysql> create table temp(id int);
Query OK, 0 rows affected (0.06 sec)

mysql> insert into temp values(null);
Query OK, 1 row affected (0.01 sec)

mysql> select count(0),count( id),max(id),min(id),avg(id),sum(id) from temp;
+----------+-----------+- --------+---------+---------+---------+
| count(0) | count(id) | max(id) | min(id) | avg(id) | sum(id) |
+----------+------------+------ ---+---------+---------+---------+
| 1 | 0 | NULL | NULL | NULL | NULL |
+----------+-----------+---------+---------+---------+---------+
1 row in set (0.00 sec)

mysql> create table temp(id int);
Query OK, 0 rows affected (0.06 sec)

mysql> insert into temp values(null);
Query OK, 1 row affected (0.01 sec)

mysql> select count(0),count(id),max(id),min(id),avg(id),sum(id) from temp;
+----------+-----------+---------+---------+---------+---------+
| count(0) | count(id) | max(id) | min(id) | avg(id) | sum(id) |
+----------+-----------+---------+---------+---------+---------+
|        1 |         0 |    NULL |    NULL |    NULL |    NULL |
+----------+-----------+---------+---------+---------+---------+
1 row in set (0.00 sec)
Aggregation functions (max, min, sum, avg and count) ignore null values, but it does not mean that aggregate functions do not return null values: if the data table is empty, or the aggregate column values ​​are all null, then max, min, sum, avg Aggregate function returns null value while count aggregate function returns 0. Commonality of aggregate functions: Null values ​​are ignored.

No more confusion: when no value is returned, the database engine is unsure of the return value, and converts no value to a NULL value.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326869342&siteId=291194637