How can I customize the output of MySQL SUM() function to 0 instead of NULL when there are no matching rows?


As we know that the SUM() function returns NULL if there is no matching row but sometimes we want it to return zero instead of NULL. For this purpose, we can use the MySQL COALESCE() function which accepts two arguments and returns the second argument if the first argument is NULL, otherwise, it returns the first argument. To understand the above concept, consider an ‘employee_tbl’ table, which is having 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, MySQL SUM() function returns 0 when we use COALESCE function with SUM() to find the total number of pages typed by ‘Mohan’, the name which is not in the ‘Name’ column −

mysql> SELECT COALESCE(SUM(daily_typing_pages),0)AS ‘SUM(daily_typing_pages)’FROM employee_tbl WHERE Name = ‘Mohan’;
+-------------------------+
| SUM(daily_typing_pages) |
+-------------------------+
|           0             |
+-------------------------+
1 row in set (0.00 sec)

Updated on: 22-Jun-2020

168 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements