Processing of NULL values in the MySQL database

Source: Internet
Author: User

We all know that MySQL database NULL has a very unique logic significance. The handling of NULL values is a headache. So today I specially sorted out some practical TIPS, I hope to provide you with some help in this regard. If you have any omissions, please criticize them.

1. Sort columns with null values

Table creation:

 
 
  1. mysql> create table t1(col1 int primary key, col2 varchar(2),col3 int);   
  2. Query OK, 0 rows affected (0.24 sec)  

Add data:

 
 
  1. mysql> insert into t1 values (1,'A',10),(2,'B',NULL),(3,'C',NULL),(4,'D',50),(5,'E',30),(6,'F',NULL),(7,'G',20),(8,'H',90),(9,'I',NULL),(10,'J',60);   
  2. Query OK, 10 rows affected (0.08 sec)   
  3. Records: 10 Duplicates: 0 Warnings: 0  

We know that MySQL always treats NULL as the "minimum value" during sorting. For example:

 
 
  1. mysql> select * FROM t1 order by 3;   
  2. +------+------+------+   
  3. | col1 | col2 | col3 |   
  4. +------+------+------+   
  5. | 6 | F | NULL |   
  6. | 2 | B | NULL |   
  7. | 3 | C | NULL |   
  8. | 9 | I | NULL |   
  9. | 1 | A | 10 |   
  10. | 7 | G | 20 |   
  11. | 5 | E | 30 |   
  12. | 4 | D | 50 |   
  13. | 10 | J | 60 |   
  14. | 8 | H | 90 |   
  15. +------+------+------+   
  16. 10 rows in set (0.00 sec)   

However, how to achieve the following results:

 
 
  1. +------+------+------+   
  2. | col1 | col2 | col3 |   
  3. +------+------+------+   
  4. | 1 | A | 10 |   
  5. | 7 | G | 20 |   
  6. | 5 | E | 30 |   
  7. | 4 | D | 50 |   
  8. | 10 | J | 60 |   
  9. | 8 | H | 90 |   
  10. | 2 | B | NULL |   
  11. | 3 | C | NULL |   
  12. | 6 | F | NULL |   
  13. | 9 | I | NULL |   
  14. +------+------+------+  
  15. 10 rows in set (0.00 sec)   
  16. SOLUTION:   
  17. mysql> SELECT col1, col2, col3 FROM (   
  18. -> SELECT col1, col2, col3,CASE WHEN col3 IS NULL THEN 0 ELSE 1 END AS IS_NULL FROM t1) as n   
  19. -> ORDER BY n.IS_NULL DESC, col3;  

Use the 'case' expression to construct an additional column, assign values to null values and non-null values respectively, and then use this additional column as the sorting condition.

 
 
  1. mysql> select col1, col2, col3,CASE WHEN col3 IS NULL THEN 0 ELSE 1 END AS IS_NULL FROM t1;   
  2. +------+------+------+---------+ |  
  3. | col1 | col2 | col3 | IS_NULL |   
  4. +------+------+------+---------+   
  5. | 1 | A | 10 | 1 |   
  6. | 2 | B | NULL | 0 |   
  7. | 3 | C | NULL | 0 |   
  8. | 4 | D | 50 | 1 |   
  9. | 5 | E | 30 | 1 |   
  10. | 6 | F | NULL | 0 |  
  11. | 7 | G | 20 | 1 |   
  12. | 8 | H | 90 | 1 |   
  13. | 9 | I | NULL | 0 |   
  14. | 10 | J | 60 | 1 |   
  15. +------+------+------+---------+   
  16. 10 rows in set (0.00 sec)   

By constructing an additional column to sort NULL columns in the MySQL database, you can easily determine the position of records containing NULL values in the result set.

2. Use order by null to disable sorting.

If the query contains group by but we want to avoid sorting the result set to reduce consumption, we can use order by null to disable sorting.

 
 
  1. R,'` A.Kk   
  2. mysql> EXPLAIN SELECT SUM(col3),CASE WHEN col3 IS NULL THEN 0 ELSE 1 END AS IS_NULL FROM t1 GROUP BY IS_NULL\G;  

1. row

 
 
  1. id: 1   
  2. select_type: SIMPLE   
  3. table: t1   
  4. type: ALL    
  5. possible_keys: NULL   
  6. key: NULL   
  7. key_len: NULL   
  8. ref: NULL   
  9. rows: 10   
  10. Extra: Using temporary; Using filesort   
  11. 1 row in set (0.00 sec)   
  12. mysql> EXPLAIN SELECT SUM(col3),CASE WHEN col3 IS NULL THEN 0 ELSE 1 END AS IS_NULL FROM t1 GROUP BY IS_NULL m)ORDER BY NULL\G;   

1. row

 
 
  1. id: 1   
  2. select_type: SIMPLE   
  3. table: t1   
  4. type: ALL   
  5. possible_keys: NULL   
  6. key: NULL   
  7. key_len: NULL ts   
  8. ref: NULL   
  9. rows: 10   
  10. Extra: Using temporary   
  11. 1 row in set (0.00 sec)  

Obviously, if order by null is used, no filesort is performed for the query. In large result sets, the filesort operation is usually quite time-consuming.

3. subquery not in and NOT EXISTS NULL

IN some cases, a subquery in the not in form returns an empty result set, but changes it to the not exists form, and then returns to normal, as shown below:
Table creation:

 
 
  1. mysql> CREATE TABLE t2 (col1 int default NULL, col2 int default NULL);   
  2. Query OK, 0 rows affected (0.01 sec)   
  3. mysql> CREATE TABLE t3 (col1 int default NULL, col2 int default NULL);   
  4. Query OK, 0 rows affected (0.01 sec)  

Add data:

 
 
  1. mysql> INSERT INTO t2 VALUES (1,2),(1,3);   
  2. Query OK, 2 rows affected (0.00 sec)   
  3. Records: 2 Duplicates: 0 Warnings: 0   
  4. mysql> INSERT INTO t3 VALUES (1,2),(1,NULL);   
  5. Query OK, 2 rows affected (0.00 sec)   
  6. Records: 2 Duplicates: 0 Warnings: 0  

Execute the following query:

 
 
  1. mysql> SELECT * FROM t2 WHERE col2 NOT IN (SELECT col2 FROM t3);   
  2. Empty set (0.00 sec)   
  3. mysql> SELECT * FROM t2 WHERE NOT EXISTS (SELECT 1 FROM t3 WHERE t3.col2 = t2.col2);   
  4. +------+------+   
  5. | col1 | col2 |   
  6. +------+------+   
  7. | 1 | 3 |   
  8. +------+------+   
  9. 1 row in set (0.00 sec)  

Why? This should begin with the particularity of MySQL database NULL:

There are three statuses in MySQL: True, False, and Unknown. Any NULL comparison operation is in the Unknown status, as shown below:

 
 
  1. mysql> SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL;   
  2. +----------+-----------+----------+----------+   
  3. | 1 = NULL | 1 <> NULL | 1 < NULL | 1 > NULL |   
  4. +----------+-----------+----------+----------+   
  5. | NULL | NULL | NULL | NULL |   
  6. +----------+-----------+----------+----------+   
  7. 1 row in set (0.00 sec)  

All query conditions, such as ON, WHERE, and HAVING, process the Unknown state as False.

Therefore, the first query field is equivalent to: col2 not in (2, NULL) => col2 <> 2 AND col2 <> NULL => true AND Unknow => False
The query condition is always False, so no results are returned for this query.

Not exists is executed cyclically.

He first runs SELECT 1 FROM t3 WHERE t3.col2 = 2

The returned results are NOT output because the query condition is False after the not exists operation,

Next, run SELECT 1 FROM t3 WHERE t3.col2 = 3.

No response is returned. After the not exists operation, the query condition is True, and the query result is output.

Therefore, if a not in subquery does NOT return results, pay special attention to whether the result set of the inner query contains null values. If yes, you should try to rewrite the query to not exists format.

This can also lead to performance improvement in some cases. The above content is an introduction to MySQL database NULL. I hope you will get some benefits.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.