English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to return '0' using SUM function in MySQL if a value is not found?

To return '0' as Sum when no value is found, use the IFNULL or COALESCE command.

The following is the syntax of IFNULL.

SELECT IFNULL(SUM(NULL), 0) AS aliasName;

Now let's implement the above syntax in the following query.

mysql> SELECT IFNULL(SUM(NULL), 0) AS SUMOFTWO;

The following is the output of the above query, returning 0.

+----------+
| SUMOFTWO |
+----------+
|  0  |
+----------+
1 row in set (0.00 sec)

This is the syntax of COALESCE.

mysql> SELECT COALESCE(SUM(NULL),0) as SUMOFTWO;

The following is the use of theSUM()Function returns 0 output.

+----------+
| SUMOFTWO |
+----------+
|  0  |
+----------+
1 row in set (0.00 sec)