Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return NULL when result is empty?

Tags:

sql

mysql

I have a simple query that selects one field and only one row, thus one value.

Is there any way to make it return NULL if the query results in an empty set? Instead of returning zero rows?

I think I need to use something with NOT EXISTS, THEN NULL but not certain about it.

like image 720
silkfire Avatar asked Jun 22 '13 11:06

silkfire


People also ask

How return null instead of blank in SQL?

There are two ways to replace NULL with blank values in SQL Server, function ISNULL(), and COALESCE(). Both functions replace the value you provide when the argument is NULL like ISNULL(column, '') will return empty String if the column value is NULL.

Does return 0 count null?

As all of your values are null, count(cola) has to return zero. Save this answer.

Can SQL query return null?

Description. The IS NULL condition is used in SQL to test for a NULL value. It returns TRUE if a NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.

How do you return an empty value in Java?

In Java, a null value can be assigned to an object reference of any type to indicate that it points to nothing. The compiler assigns null to any uninitialized static and instance members of reference type. In the absence of a constructor, the getArticles() and getName() methods will return a null reference.


2 Answers

select
  (Your entire current Select statement goes here) as Alias
from 
  dual

dual is a built in table with a single row that can be used for purposes like this. In Oracle this is mandatory. MySQL supports it, but you can also just select a single value without specifying a table, like so:

select
  (Your entire current Select statement goes here) as Alias

In either case you're selecting a single value. This means that:

  • If your select returns one value, that value is returned.
  • If your select statement returns one column, but no rows, NULL will be returned.
  • If your select statement returns multiple columns and/or multiple rows, this won't work and the query fails.
like image 186
GolezTrol Avatar answered Sep 25 '22 00:09

GolezTrol


An easy way to do this is with aggregation:

select max(col)
from t
where <your condition here>

This always returns one row. If there is no match, it returns NULL.

like image 35
Gordon Linoff Avatar answered Sep 22 '22 00:09

Gordon Linoff