I need to write a query that returns the sum of all values that meet a certain criteria, but the query needs to return 0 if no rows are found, rather than null. For example:
tab
+---------------+-----+
| descr | num |
+---------------+-----+
| hello there | 5 |
| hi there | 10 |
| hello | 10 |
| hi there! | 15 |
+---------------+-----+
This query:
SELECT sum(num) AS val FROM tab WHERE descr LIKE "%hello%";
should, and does, return 15
. However:
SELECT sum(num) AS val FROM tab WHERE descr LIKE "%greetings%";
should return 0
, but does return null
.
Can someone explain if this is possible?
How about:
The COALESCE function basically says "return the first parameter, unless it's null in which case return the second parameter" - It's quite handy in these scenarios.
To do this properly, you may want to distinguish between the case where there are actual
NULL
results in the data you're summing, and the case where there are no values at all to sum.Suppose we have the following:
We would like empty sums to be zero, but sums involving
NULL
to beNULL
. One (rather torturous) way to do that is:Perhaps there's a better way I haven't thought of.
Unfortunately, the SQL standard defines
SUM
to be null when no elements are summed, and MySQL has no choice but to follow that standard.This works:
IF() takes three parameters: (1) A statement, (2) the value to apply if the statement is true, and (3) the value to apply if the statement is false.
Check the MySQL documentation for IFNULL.
Of course, this assumes your
num
field is nullable and doesn't have a default value. Another possible solution would be to set a default of0
for the num field which should solve the issue you're having.