MySQL - query to return NULL

advertisements

I have the following code:

SELECT q25, (
(
AVG( q1 ) + AVG( q2 ) + AVG( q3 ) ) /3 ) AS Overall
FROM t_results
WHERE brand =  'XYZ'
AND DATE =  'MAY2012'
GROUP BY q25
ORDER BY Overall
DESC LIMIT 1

If there is no data found by the query phpmyadmin returns the following message (which is quite correct):

MySQL returned an empty result set (i.e. zero rows). ( Query took 0.0178 sec )

However, what I'd like is to actually return a NULL value, is this possible? I appreciate this might not be best practise but I'm working with inherited code and this might be the simplist and quickest route to a solution.

Thanks as always,

H.


Create a table with exactly one row. Then you can use left join to achieve the desired NULL result.

CREATE TABLE dummy (d TINYINT NOT NULL);
INSERT INTO dummy SET d = 1;

SELECT q25,
       ( ( AVG( q1 ) + AVG( q2 ) + AVG( q3 ) ) /3 ) AS Overall
FROM dummy LEFT JOIN t_results
  ON brand = 'XYZ'
 AND DATE = 'MAY2012'
GROUP BY q25
ORDER BY Overall DESC
LIMIT 1

You can also replace the dummy table with a subquery:

SELECT q25,
       ( ( AVG( q1 ) + AVG( q2 ) + AVG( q3 ) ) /3 ) AS Overall
FROM (SELECT 1) AS dummy LEFT JOIN t_results
  ON brand =  'XYZ'
 AND DATE =  'MAY2012'
GROUP BY q25
ORDER BY Overall DESC
LIMIT 1

Tested this via sqlfiddle, where you can also experiment with alternatives.

The conditions selecting the result, which used to be in the WHERE clause, now have to go into the ON clause. Otherwise the left join would produce non-NULL rows which would be removed by the WHERE, instead of generating a single NULL row if no matching row could be found. If there were no WHERE conditions in the original query, ON 1 could be used to express any row matches.