How to select sum -or- 0 if no records exist?

前端 未结 4 949
闹比i
闹比i 2020-12-09 14:48

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

4条回答
  •  無奈伤痛
    2020-12-09 15:23

    This works:

    SELECT IF(SUM(num) IS NULL, 0, SUM(num)) AS val FROM tab WHERE descr LIKE "%whatever%";
    

    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.

提交回复
热议问题