Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can IFNULL be used with select statements for a sum?

Tags:

sql

mysql

I have two tables with a decimal value, using the following statement I can add them all up and get the total.

SELECT(
(SELECT SUM(total) from recruitment where quote_id = 1)
+
(SELECT SUM(cost) from cost WHERE quote_id = 1)
)AS total

But if either select reurns null then the the total is null so I tried using ISNULL to return a 0 rather than null like this:

SELECT(
(IFNULL(SELECT SUM(total) FROM recruitment WHERE quote_id = 1),0)
+
(IFNULL(SELECT SUM(cost) FROM cost WHERE quote_id = 1),0)
)AS total

This didn't work, so I was just wondering how is the best way to go about doing this?

like image 415
sore-spot Avatar asked Dec 26 '22 15:12

sore-spot


1 Answers

Use COALESCE() which returns its first non-null argument, and can replace the whole expression with a zero.

SELECT(
  COALESCE((SELECT SUM(total) FROM recruitment WHERE quote_id = 1),0)
  +
  COALESCE((SELECT SUM(cost) FROM cost WHERE quote_id = 1),0)
)AS total

IFNULL() should work the same way in this case - I suspect you may have had incorrect parentheses causing a syntax error.

/* Should work too. Make sure the inner SELECT is enclosed in () */
SELECT(
  IFNULL((SELECT SUM(total) FROM recruitment WHERE quote_id = 1),0)
  +
  IFNULL((SELECT SUM(cost) FROM cost WHERE quote_id = 1),0)
)AS total
like image 61
Michael Berkowski Avatar answered Jan 10 '23 04:01

Michael Berkowski