Oracle 9i Queries: Handling NULL and Empty Strings Effectively
Why Oracle 9i Might Seem to Treat Empty Strings as NULL
- NULL: Represents the absence of a value. It signifies "unknown" or "not applicable."
- Empty String: A string with zero characters, but it still occupies space in memory and has a length of 0.
Similarities in Behavior:
- Comparisons: Comparing an empty string with NULL using
=
or<=>
will always return FALSE. This is because NULL represents an unknown value, and comparing it with anything results in unknown (FALSE). IS NULL
Operator: Both NULL and empty strings evaluate to TRUE when used with theIS NULL
operator. This operator specifically checks for the absence of a value, regardless of whether it's NULL or an empty string.
Example:
-- Create a table
CREATE TABLE my_table (
id NUMBER,
name VARCHAR2(20)
);
-- Insert some data
INSERT INTO my_table VALUES (1, 'foo');
INSERT INTO my_table VALUES (2, ''); -- Insert an empty string
-- Select rows
SELECT * FROM my_table WHERE name = ''; -- Doesn't return any rows
SELECT * FROM my_table WHERE name IS NULL; -- Returns both rows (including the empty string)
Important Points:
- Not always equivalent: While comparisons with
=
or<=>
and theIS NULL
operator behave similarly, empty strings are not the same as NULL in all contexts. Functions likeLENGTH
will return 0 for an empty string, while it's impossible to determine the "length" of NULL. - Historical behavior: In earlier versions of Oracle, empty strings were indeed treated as NULL. This behavior changed in later versions, but some functionalities might still exhibit remnants of this history.
Related Issues and Solutions:
- Inconsistent behavior: If you need consistent behavior across different database versions, explicitly check for both NULL and empty strings in your queries using
IS NULL
and string comparisons. - Data integrity: In case you intend to store true missing information, use NULL explicitly instead of relying on empty strings. This ensures clarity and consistency.
sql oracle null