
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Customize MySQL SUM Function Output to 0 Instead of NULL
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)
Advertisements