Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return NULL value when MySQL returned an empty result set

Tags:

sql

mysql

I have a query as shown below.

 select a.ab as new from tab a inner join tab b on a.ab=b.ab 

When i try to run its showing.

  MySQL returned an empty result set (i.e. zero rows). 

because there are no rows for the selected condition.

Actual output i need is.

 new
 ----
 NULL

So i tried to add this query below.

 select COALESCE(a.ab,'') as new from tab a inner join tab b on a.ab=b.ab 

Still its giving

 MySQL returned an empty result set (i.e. zero rows).

So how it is possible to display NULL value when MYSQL returns empty set.Any help appreciated.

like image 461
Shreyas Achar Avatar asked Mar 05 '15 07:03

Shreyas Achar


People also ask

Is empty set NULL in MySQL?

As it happened in your case, mysql gave it an empty value instead. Empty value is not equivalent to NULL value as one can see by trying to get length of fields. Length of empty would be 0, while that of NULL would be NULL.

Why MySQL returned an empty result set?

An empty result set is returned if there are no rows returned. (An empty result set differs from a null pointer as a return value.) After you have called mysql_store_result() and gotten back a result that is not a null pointer, you can call mysql_num_rows() to find out how many rows are in the result set.

Can MySQL function return NULL?

We can return 0 for NULL in MySQL with the help of IFNULL() method. The syntax of IFNULL() is as follows. IFNULL(YOUREXPRESSION,0);

How do I assign a default value if no rows returned from the select query MySQL?

You can use IFNULL() function from MySQL to return a value even if there is not result.


2 Answers

You can just use the Outer select. Encapsulate the query with the Outer select, if you want actual NULL value from the database in case of 0 rows,

SELECT 
    (
      SELECT a.ab 
      FROM 
          tab a INNER JOIN tab b 
           ON a.ab=b.ab
    ) As New;

You can use the alternative with UNION ALL and LIMIT as,

      SELECT a.ab 
      FROM 
          tab a INNER JOIN tab b 
           ON a.ab=b.ab
      UNION ALL 
      SELECT NULL
      LIMIT 1
like image 105
Mahesh Avatar answered Oct 22 '22 09:10

Mahesh


If you want that the result is null when you have 0 rows try this statement:

IF EXISTS (SELECT 1 FROM TAB AS A INNER JOIN TAB AS B ON A.AB = B.AB )
BEGIN
     SELECT A.AB AS NEW FROM TAB AS A INNER JOIN TAB AS B ON A.AB = B.AB 
END
ELSE
BEGIN
    SELECT NULL AS NEW
END
like image 29
Galma88 Avatar answered Oct 22 '22 08:10

Galma88