Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle nulls in NOT IN and NOT LIKE statements in Oracle?

I have a long piece of PL/SQL which is working well except for one small part of the where clause.

I'm expecting that one row should be returned but, because the fields the where clause checks are null, the row is not being returned despite meeting the criteria.

I read a very good note here :
http://jonathanlewis.wordpress.com/2007/02/25/not-in/

It explains how Nulls affect NOT IN statements and I presume it's the same for NOT LIKE as well.

What I haven't been able to find is the comparable replacement I need. Do I need to somehow switch this into an IN and LIKE or provide something to return the row if NUll?

Here is a simplified version of my code.

SELECT * FROM Temp_Table T
WHERE -- Other where constraints
AND (T.Col_One NOT LIKE 'AString'
     OR T.Col_Two NOT IN ('BString','CString'))

In my situation the row would have nulls in both Col_One and Col_Two.

Any help is greatly appreciated.

Thanks.

like image 204
dee Avatar asked Jun 26 '12 20:06

dee


People also ask

How do you handle null values in CASE statement in Oracle?

Answers. You could use the NVL statement to check for NULLs. Something like: WHEN NVL(column_value,'XXX') = 'XXX' THEN ...

How are NULLs treated in Oracle?

Oracle Database currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as nulls. Any arithmetic expression containing a null always evaluates to null.

Does != Include null SQL?

So basically when we use != or NOT IN in query, it ignores the records with NULL values for fields. The above queries will consider records with state having a NOT NULL value, but state having a NULL value will not be considered.

How do you replace not in with not exists in Oracle?

You can usually use IN sub-queries to get the same results as EXISTS sub-queries: For example: SELECT c, d, e, f FROM a WHERE (c, d, e) NOT IN ( SELECT c, d, e FROM b ) ; An anti-join is another way, but it would probably be less efficient than either NOT IN or NOT EXISTS.


2 Answers

Something like this should work:

T.Col_One IS NULL OR T.Col_One NOT LIKE 'AString'
OR T.Col_Two IS NULL OR T.Col_Two NOT IN ('BString','CString')

Please note that...

T.Col_Two NOT IN ('BString','CString') 

...is equivalent to...

T.Col_Two <> 'BString' AND T.Col_Two <> 'CString'

...which "collapses" to NULL in case T.Col_Two is NULL.

like image 44
Branko Dimitrijevic Avatar answered Sep 28 '22 00:09

Branko Dimitrijevic


Try this:

AND (NVL(T.Col_One,'NuLl') NOT LIKE 'AString'
      OR NVL(T.Col_Two,'NuLl') NOT IN ('BString','CString')) 
like image 97
DCookie Avatar answered Sep 28 '22 00:09

DCookie