In MySQL, the SUM function can return NULL if no values are found. This can be problematic when you want the function to return 0 instead.
Consider the following query:
SELECT SUM(Column_1) FROM Table WHERE Column_2 = 'Test'
If no entries in Column_2 contain the text 'Test', the function returns NULL.
To avoid this issue, you can use the COALESCE function. COALESCE takes two arguments: a value and a default value. If the value is NULL, COALESCE returns the default value.
Here's how you can use COALESCE with SUM:
SELECT COALESCE(SUM(Column_1), 0) FROM Table WHERE Column_2 = 'Test'
Now, if no entries in Column_2 contain the text 'Test', the function will return 0 instead of NULL.
You can see this in action in the SQL Fiddle here: http://www.sqlfiddle.com/#!2/d1542/3/0
This example demonstrates how COALESCE can be used to return 0 when no values are found in a SUM function.
The COALESCE function can be used with any value or expression. It's a versatile tool that can be used to handle NULL values in various situations.
The above is the detailed content of How to Avoid NULL SUM Return in MySQL?. For more information, please follow other related articles on the PHP Chinese website!