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.
Answers. You could use the NVL statement to check for NULLs. Something like: WHEN NVL(column_value,'XXX') = 'XXX' THEN ...
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.
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.
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.
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.
Try this:
AND (NVL(T.Col_One,'NuLl') NOT LIKE 'AString'
OR NVL(T.Col_Two,'NuLl') NOT IN ('BString','CString'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With