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

前端 未结 4 965
闹比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:19

    How about:

    SELECT COALESCE(sum(num), 0) AS val FROM tab WHERE descr LIKE "%greetings%";
    

    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.

提交回复
热议问题