Return 0 when SUM is NULL

Asked

Viewed 1,324 times

6

When you find no results you return to me NULL, how can I make the search return me 0 when it is NULL?

SELECT SUM(coluna1 + coluna2 + coluna3) 
 FROM table WHERE nome='funalo' AND MONTH(data) = 09 AND YEAR(data) = 2018
  • SELECT SUM(COALESCE(coluna1, 0) + COALESCE(coluna2, 0) + COALESCE(coluna3, 0)) FROM table WHERE nome='funalo' AND MONTH(data) = 09 AND YEAR(data) = 2018

  • See if that’s what you need

  • Turns me null the same way :/

2 answers

8


Use IFNULL().

Definition and use: The IFNULL() function allows returning an alternative value if an expression is NULL. If the expression is NOT NULL, the IFNULL() function will return the expression. Source: W3schools

SELECT IFNULL(SUM(coluna1 + coluna2 + coluna3), 0)
FROM table
WHERE nome='funalo' AND MONTH(data) = 09 AND YEAR(data) = 2018
  • Oops, it worked thank you very much Brother :]

5

Just put a IFNULL in your consultation:

SELECT  IFNULL(SUM(coluna1 + coluna2 + coluna3), 0) AS Soma
FROM    table 
WHERE   nome        = 'funalo' 
    AND MONTH(data) = 09 
    AND YEAR(data)  = 2018
  • Unfortunately it didn’t work :[

  • Sorry, it’s Mysql, I didn’t notice, my mistake. Answer edited.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.