Returning a value even if no result

MySQL has a function to return a value if the result is null. You can use it on a whole query:

SELECT IFNULL( (SELECT field1 FROM table WHERE id = 123 LIMIT 1) ,'not found');

As you are looking for 1 record, (LIMIT 1) then this will work.

(SELECT field1 FROM table WHERE id = 123) 
UNION 
(SELECT 'default_value_if_no_record')
LIMIT 1;

Can be a handy way to display default values, or indicate no results found. I use it for reports.

See also http://blogs.uoregon.edu/developments/2011/03/31/add-a-header-row-to-mysql-query-results/ for a way to use this to create headers in reports.


You could include count(id). That will always return.

select count(field1), field1 from table where id = 123 limit 1;

http://sqlfiddle.com/#!2/64c76/4


You can use COALESCE

SELECT COALESCE(SUM(column),0)
FROM   table

If someone is looking to use this to insert the result INTO a variable and then using it in a Stored Procedure; you can do it like this:

DECLARE date_created INT DEFAULT 1;
SELECT IFNULL((SELECT date FROM monthly_comission WHERE date = date_new_month LIMIT 1), 0) 
INTO date_created 
WHERE IFNULL((SELECT date FROM monthly_comission WHERE date = date_new_month LIMIT 1), 0) = 0;

With this you're storing in the variable 'date_created' 1 or 0 (if returned nothing).