When the MySQL SUM() function is used with a SELECT statement that returns no matching rows, then there is nothing to evaluate and it returns NULL as output. Sometimes, we think it must return 0 as output, but 0 itself is a number, and for rows with no matches, it doesn't matter that it returns 0, so it returns NULL. To understand the above concept, consider an "employee_tbl" table which has the following records -
mysql> SELECT * FROM employee_tbl; +------+------+------------+--------------------+ | id | name | work_date | daily_typing_pages | +------+------+------------+--------------------+ | 1 | John | 2007-01-24 | 250 | | 2 | Ram | 2007-05-27 | 220 | | 3 | Jack | 2007-05-06 | 170 | | 3 | Jack | 2007-04-06 | 100 | | 4 | Jill | 2007-04-06 | 220 | | 5 | Zara | 2007-06-06 | 300 | | 5 | Zara | 2007-02-06 | 350 | +------+------+------------+--------------------+ 7 rows in set (0.00 sec)
Now, when we run the following query to find the input of "Mohan" (a name that is not in the "Name" column) When the total number of pages is reached, the MySQL SUM() function returns NULL -
mysql> SELECT SUM(daily_typing_pages) FROM employee_tbl WHERE Name = ‘Mohan’; +-------------------------+ | SUM(daily_typing_pages) | +-------------------------+ | NULL | +-------------------------+ 1 row in set (0.00 sec)
The above is the detailed content of How does the MySQL SUM() function evaluate whether it is used with a SELECT statement that returns unmatched rows?. For more information, please follow other related articles on the PHP Chinese website!