Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to NOT select empty string

Tags:

java

mysql

orm

jpa

We have the following JPQL:

Select distinct sys.ipAddress from SystemLog sys where sys.ipAddress is not null and sys.ipAddress is not empty

And this generates the following mysql statement.

select
    distinct systemlog0_.ipAddress as col_0_0_ 
from
    SystemLog systemlog0_ 
where
    (
        systemlog0_.ipAddress is not null
    ) 
    and (
        exists (
            select
                systemlog0_.id 
            from
                SystemLog systemlog0_
        )
    )

This obviously doesn't work and returns empty string instead of omitting it. However, I am looking for something like this to be generated:

select distinct ipAddress from SystemLog where ipAddress is not null and ipAddress <> '';

However, I can't figure out why our jpa query doesn't generate something simliar like that. Any ideas?

like image 565
Shervin Asgari Avatar asked Aug 05 '10 15:08

Shervin Asgari


People also ask

How do you write not empty in SQL?

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

Does coalesce work on empty string?

If all the arguments are blank or empty strings then the function returns blank, making Coalesce a good way to convert empty strings to blank values.

How do I filter empty records in SQL?

The IS NULL operator is used to test for empty values (NULL values).

Is NULL or empty in SQL?

A null value in a database really means the lack of a value. It is a special “value” that you can't compare to using the normal operators. You have to use a clause in SQL IS Null. On the other hand, an empty string is an actual value that can be compared to in a database.


1 Answers

I think that you are misusing IS [NOT] EMPTY that is used to check whether a collection association path resolves to an empty collection or has at least one value. From the JPA specification:

4.6.11 Empty Collection Comparison Expressions

The syntax for the use of the comparison operator IS EMPTY in an empty_collection_comparison_expression is as follows:

collection_valued_path_expression IS [NOT] EMPTY

This expression tests whether or not the collection designated by the collection-valued path expression is empty (i.e, has no elements).

Example:

SELECT o
FROM Order o
WHERE o.lineItems IS EMPTY

If the value of the collection-valued path expression in an empty collection comparison expression is unknown, the value of the empty comparison expression is unknown.

In my opinion, you should just use the <> comparison operator:

select distinct sys.ipAddress 
  from SystemLog sys 
 where sys.ipAddress is not null 
   and sys.ipAddress <> ''
like image 81
Pascal Thivent Avatar answered Sep 21 '22 05:09

Pascal Thivent