JPQL / SQL query: where like '%' include null values - mysql

I have a simple JPQL query. (But this applies also to an sql query..)
FROM DomainObj d where d.field1 like 'TEST%' and d.field2 like '%';
If the DB contains the following row:
1) field1 -> 'TEST'; field2 -> null
the query return nothing!
If the DB contains the following values:
2) filed1 -> 'TEST'; field2 -> ''
the query return the row!
How can I include also null values while searching for like '%' keeping the query as simple as possible (avoiding and/or clause?)
I'm implementing searching funcionality of an entity in the db.. and I also search by many fields at the same time..
Thank you
Marco

You can't directly use nulls in equality tests, because null is un-equal to everything, including itself. That's why there's the is null test, e.g:
select null = null -> null
select null <> null -> null
select 1 = null -> null
select 1 <> null -> null
select 1 + null -> null
essentially null is contagious, and will nullify anything it's compared to, or added in to.
So yes, you'll have to do
SELECT ... WHERE somefield LIKE '%...%' or somefield IS NULL

Try this:
...
and IFNULL(d.field2, '') like '%'

...
where ...
and (field2 = '' or field2 is null)
Note that the condition field2 like '%' is nonsensical because it matches any text except null. If you added or field2 is mull to it you would match everything, so logically you should just remove the condition on field2

Use IS NULL:
where d.field1 like 'TEST%' OR d.field2 IS NULL;

FROM DomainObj d where (d.field1 like 'TEST%' or d.field1 IS NULL) and (d.field2 like '%' or d.field2 IS NULL)

Related

how to send "" instead of null in select * statement SQL

SELECT * FROM specifications
I want to send "" or "0" instead of null[if any column having null value],
can't use column-wise, more than 80 columns
As mentioned in the comments, the only way is to use COALESCE() OR ISNULL() as many times as the count (80) of your columns.
Just to make it easier, you can use the below query to generate that 80 statements for you.
SELECT CONCAT('ISNULL(',COLUMN_NAME ,',' ,
(CASE WHEN DATA_TYPE ='int' THEN '0'
WHEN DATA_TYPE ='varchar' THEN '' ELSE '' END) , ')' )
AS DERIVED_COLUMN
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'specifications'
CHECK SAMPLE DEMO HERE
Note : This is under the assumption that all your column are of int or varchar datatype. If you have other datatypes, modify the CASE accordingly.

Mysql: CONCAT_WS('', col) vs (col is null OR col=0)

Is there any difference between:
CONCAT_WS('', column)=''
AND
column is null OR column=0 *(and optionally 'OR column="" ')*
Is one of them better/faster...?
SELECT my_fields FROM my_table
WHERE my_terms_clause='anything' AND CONCAT_WS( '', nb_check ) = ''
OR
SELECT my_fields FROM my_table
WHERE my_terms_clause='anything' AND (p.nb_check is null OR p.nb_check = 0)
I usually use "column is null OR column=0", but I just want "expert's tips".
You should definitely use:
where col is null or column = 0
First, the intention of the code is much clearer. Second, the function call prevents the optimizer from using an index. To be honest,the or also makes it hard for the optimizer to use an index.
Probably the most efficient way to write the query is using union all:
SELECT my_fields
FROM my_table p
WHERE my_terms_clause = 'anything' AND p.nb_check is null
UNION ALL
SELECT my_fields
FROM my_table p
WHERE my_terms_clause = 'anything' AND p.nb_check = 0;
This can take advantage of an index on my_table(my_terms_clause, nb_check).
If a column holds the value of 0, then concat_ws() with empty string as separator will return '0', not '', so the 2 expressions are not equal. If you need to check for null or 0, then better use that version, that actually checks this condition.

How to check if field is null or empty in MySQL?

I am trying to figure out how to check if a field is NULL or empty. I have this:
SELECT IFNULL(field1, 'empty') as field1 from tablename
I need to add an additional check field1 != "" something like:
SELECT IFNULL(field1, 'empty') OR field1 != "" as field1 from tablename
Any idea how to accomplish this?
Either use
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1
from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1
from tablename
If you only want to check for null and not for empty strings then you can also use ifnull() or coalesce(field1, 'empty'). But that is not suitable for empty strings.
Using nullif does the trick:
SELECT ifnull(nullif(field1,''),'empty') AS field1
FROM tablename;
How it works: nullif is returning NULL if field is an empty string, otherwise returns the field itself. This has both the cases covered (the case when field is NULL and the case when it's an empty string).
Alternatively you can also use CASE for the same:
SELECT CASE WHEN field1 IS NULL OR field1 = ''
THEN 'empty'
ELSE field1 END AS field1
FROM tablename.
You can use the IFNULL function inside the IF. This will be a little shorter, and there will be fewer repetitions of the field name.
SELECT IF(IFNULL(field1, '') = '', 'empty', field1) AS field1
FROM tablename
You can create a function to make this easy.
create function IFEMPTY(s text, defaultValue text)
returns text deterministic
return if(s is null or s = '', defaultValue, s);
Using:
SELECT IFEMPTY(field1, 'empty') as field1
from tablename
By trimming and comparing, we ensure we also take care of empty or tab or space character content in the field.
SELECT
CASE
WHEN LTRIM(RTRIM(col_1))='' or col_1 IS NULL THEN 'Not available'
ELSE col_1
END AS col_alias
FROM
my_table
SELECT * FROM (
SELECT 2 AS RTYPE,V.ID AS VTYPE, DATE_FORMAT(ENTDT, ''%d-%m-%Y'') AS ENTDT,V.NAME AS VOUCHERTYPE,VOUCHERNO,ROUND(IF((DR_CR)>0,(DR_CR),0),0) AS DR ,ROUND(IF((DR_CR)<0,(DR_CR)*-1,0),2) AS CR ,ROUND((dr_cr),2) AS BALAMT, IF(d.narr IS NULL OR d.narr='''',t.narration,d.narr) AS NARRATION
FROM trans_m AS t JOIN trans_dtl AS d ON(t.ID=d.TRANSID)
JOIN acc_head L ON(D.ACC_ID=L.ID)
JOIN VOUCHERTYPE_M AS V ON(T.VOUCHERTYPE=V.ID)
WHERE T.CMPID=',COMPANYID,' AND d.ACC_ID=',LEDGERID ,' AND t.entdt>=''',FROMDATE ,''' AND t.entdt<=''',TODATE ,''' ',VTYPE,'
ORDER BY CAST(ENTDT AS DATE)) AS ta
If you would like to check in PHP , then you should do something like :
$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
//do your action
echo "It was filled";
} else {
echo "it was empty!";
}

MYSQL Null issues

I've got a simple DB query. Basically I want to select all rows that are NOT equal to a certain set of strings, or is empty (if it's empty I do NOT want it to be selected).
This is what I've got:
select * from tbl_user where secretCode != ('S00' OR 'S05' OR 'A10' OR '')
The datatype of secretcode is CHAR(4), NULL (NO), DEFAULT NONE
What am I doing wrong here, should I be using NULL instead of '' ?
Thanks.
I think your query should be like this:
select * from tbl_user where secretCode NOT IN ('S00', 'S05', 'A10', '') AND
secretCode IS NOT NULL
select
*
from
tbl_user
where
secretCode not in ('S00', 'S05', 'A10') and secretCode not is null
Checking for NULL shoud be done with is null or not is null.
You should use the IS NOT NULL operator according to here
SELECT * FROM `tbl_users`
WHERE `secretCode` != ('S00' OR 'S05' OR 'A10') AND `secretCode` IS NOT NULL
use:
SELECT * FROM `tbl_users` WHERE `secretCode` <> ('S00' OR 'S05' OR 'A10') AND `secretCode` IS NOT NULL

Check field if empty

Is the query correct if I wanted to check if the field has other characters other than null and empty?
select CASE WHEN description IS NULL THEN 'null'
WHEN description IS NOT NULL THEN 'not null' ELSE 'something else' END
AS 'description'from milestone where name like '%Test%' or name like '%test%';
+-------------+
| description |
+-------------+
| not null |
+-------------+
1 row in set (0.00 sec)
Null and empty means NULL + '' (empty string)?
select CASE WHEN description IS NULL or description = '' THEN 'null or empty'
ELSE 'not null' END
AS 'description'
In your original query, there is no possibility of a third case because IS NULL and IS NOT NULL are complementary, between them they have covered all possibilities.
Also, unless you are using case-sensitive collation (very rare, and never by default unless you specifically nominate one), MySQL is not Oracle - these two queries will work the same:
where name like '%Test%' or name like '%test%'
where name like '%test%'
Because MySQL will match strings case-insensitively
Simple IF solution:
IF (my_field = '', "not null", "null")
By the way, I personally like to use it like that (shorthand syntax):
IF (my_field = '', 1, 0)
Maybe you can try something like this:
select IF(LENGTH(description) > 0,'not null', 'null or empty') from milestone
You can also try to use REGEXP:
// 0 is considered empty
WHERE `field` [NOT] REGEXP '[^0]'
// 0 is not considered empty
WHERE `field` [NOT] REGEXP '[^.]'
I would create a "stored function" (what in MSSQL is called a user-defined function):
CREATE FUNCTION isNullOrSpaces(s TEXT)
RETURNS BOOLEAN DETERMINISTIC
RETURN (IFNULL(LENGTH(TRIM(s)), 0) = 0);
select
isNullOrSpaces(null) 'null',
isNullOrSpaces('') 'empty string',
isNullOrSpaces(' ') 'spaces',
isNullOrSpaces('
') 'spaces, tab and newline';
Note that the last case - where the value contains tabs and newlines - returns 0 (FALSE). This is thanks to a bad implementation (IMHO) of the built-in TRIM function, which doesn't remove all whitespace.
I would have preferred to make the function isNullOrWhiteSpace, but since this is good enough for many cases and a pure-SQL implementation of a proper TRIM function will be slow, I figured this will do. If you need to handle all whitespace, consider making what MySQL calls a user-defined function (native function is a better name IMO) - see for instance https://www.codeproject.com/articles/15643/mysql-user-defined-functions.
You may also wish to make a version that returns empty string if the argument is NULL, empty or spaces. This version is mainly useful for the WHERE or HAVING clauses of a query, but the only difficult part of making one that works the same except returning empty string or the original string is to name the function appropriately..! Something like this:
CREATE FUNCTION trimEx(s TEXT)
RETURNS TEXT DETERMINISTIC
RETURN IF(IFNULL(LENGTH(TRIM(s)), 0) = 0, '', TRIM(s));
select
trimEx(null) 'null',
trimEx('') 'empty string',
trimEx(' ') 'spaces',
trimEx(' not empty ') 'contains text';
// checks if the field not null
where field_name !=' '