Special handling of NULL in SQL queries

Article 1 Four Arithmetic Operations

When numbers and NULL are added, subtracted, multiplied and divided, the program does not recognize NULL, so it does not know what the result of the operation is, so it can only return NULL in the end.

Article 2 Comparison operation

When we compare numbers, strings or dates with NULL, the program does not know who is bigger or smaller than NULL, or whether they are the same value, so the program can only tell you, l don't know, and the program only Will return the comparison result is True data. So, here you know the meaning of IS NULL and IS NOT NULL . These two predicates are specially responsible for dealing with NULL values.

Article 3 group by

We can understand the execution logic of group by in this way. For example, there are three non-NULL values ​​of a, b, and c in the aggregation key, and then automatically loop through each row, and compare the value of each row with a, b, and c. If they are equal, then As a result, when the NULL value is encountered, the program cannot compare, so there is no way, and finally NULL is divided into one category alone.

Article 4 Parameter passing

In the same way, when NULL is passed as a parameter to arithmetic functions, string functions, date functions, and conversion functions, the program does not know NULL and does not know how to deal with it, so the result can only return NULL .

Clause 5 Aggregate functions

According to what we said above, NULL values ​​cannot be compared, nor can they participate in calculations, so the aggregation function is more intelligent, it will automatically exclude NULL values ​​first, and only perform calculations on the remaining values , thus avoiding It's embarrassing that you can't use it as soon as you encounter a NULL value.
COUNT (a column) , if this column contains NULL values, then it will also remove the data of NULL values ​​first, so that only the number of rows with non-NULL values ​​is returned, so if you want to get all rows including NULL values number, you must use COUNT(*) .

Article 7 order by

The execution logic of order by also has a comparison process. All values ​​are sorted by comparing their sizes. Then NULL values ​​cannot be compared with other values. Therefore, when designing order by, simply pick out NULLs alone, or put them all in the most In the front, or put them all at the end, each RDBMS has a different design, and the ordering between NULL values ​​and NULL values ​​is random.

Guess you like

Origin blog.csdn.net/SingDanceRapBall/article/details/115418193
Recommended