shreesha shreesha - 7 months ago 23
SQL Question

Oracle:Difference between NULL and EMPTY string

I am in a situation where my query is not returning any values due to oracle behaviour.


Problem is this:Oracle considers EMPTY STRING as NULL when INSERTING DATA but not when SELECTING BACK the data.


This is not a duplicate of Why does Oracle 9i treat an empty string as NULL? because here i am not asking for the reason to this problem,i am well aware of the reason,i am asking for a solution to this problem.

This is my table structure

CREATE TABLE TEST
(
ID NUMBER not null,
NAME VARCHAR2(255)
)


when inserting the values oracle will accept

INSERT INTO TEST values(1,'');

I found out that internally oracle converts Strings of Zero length to NULL and stores


But my query

SELECT * FROM TEST
WHERE NAME = INPUT;(INPUT='')

(Input is passed from front end and will sometimes have empty string)

will not return any result

I can not write dynamic query due to performance issue

Somebody who faced this issue before please let me know how do i compare EMPTY STRING with NULL

Answer

This is one of the most annoying features of Oracle - not found in other DB products. You will have to put up with it, for all the other massive advantages of Oracle - and be prepared that the learning curve is not very quick.

To check for equality of nulls, the best approach is to write explicitly what you are doing, instead of using gimmicks. For example:

... where NAME = INPUT or (NAME IS NULL and INPUT IS NULL)

This will make it a lot easier for yourself, and for others after you, to debug, maintain, and modify the code, now and especially later. There are other solutions, too, but they may confuse others in the future; for example, this is something I wouldn't use (for several reasons):

... where NAME || 'z' = INPUT || 'z'

although it would obviously achieve the same result with less typing.

One more thing, in most cases you should NOT include in your results rows where you treat NULL as "equal" - the values are NULL for a reason, and in most cases if you make two NULL's equal, that is NOT the intended result.

Comments