2

is there a way where I can return 0 if i get an empty result in mysql?

SELECT t1.amount as Amt
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.project_id = t2.id

WHERE t2.proj_name = "Project_Kalinga"
AND t1.date_sent = (SELECT MAX(date_sent) FROM table WHERE project_id = "0123")

Currently for the project name 'Project Kalinga' I get an empty result.

Is there a way where from this query even if i get an empty result, I'll just get 0 instead? So then the output would be like

| Amt |
|  0  |

Thank You!

Here's the sqlfiddle

http://sqlfiddle.com/#!2/0c4c5/2

2 Answers 2

4

You can

  • create a "Dummy row" with zero
  • do a left join to your main query.
  • Coalesce the real value and the dummy value

SELECT Coalesce(t1.amt, d.amount) AS amt 
FROM   (SELECT 0 as amount
        FROM   DUAL) AS d
       LEFT JOIN  
       (SELECT t1.amount AS Amt 
        FROM   table1 AS t1 
               INNER JOIN table2 AS t2 
                       ON t1.project_id = t2.id 
        WHERE  t2.proj_name = "project_kalinga" 
               AND t1.date_sent = (SELECT Max(date_sent) 
                                   FROM   table1 
                                   WHERE  project_id = "0123")) AS t1 
       ON 1 = 1

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

nevermind, got it. Thanks! just changed t1.amount to t1.Amt
@hearmeroar I also used "table" when I should have used "table1" Thanks for the fiddle btw. It makes everything eaiser
2

Try this:

SELECT IFNULL(t1.amount,0) as Amt
FROM table t1
LEFT OUTER JOIN table2 t2
ON t1.project_id = t2.id AND t2.proj_name = "Project_Kalinga"
WHERE t1.date_sent = (SELECT MAX(date_sent) FROM table WHERE project_id = "0123")

3 Comments

It didn't work for me either. Still getting the error MySQL returned an empty result set and it didn't return any rows
@hearmeroar: Can you show me some contents of the table, please?
still didn't work. Here is the requested content sqlfiddle.com/#!2/0c4c5/2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.