Sub topic 9
Edge cases: position 0, no match, zero length, and NULL
This chapter assumes you can write a basic SELECT with WHERE, you know that dual is a one-row table for testing expressions, and you have used SUBSTR, INSTR, and REPLACE on ordinary input. Here you will learn what each function returns when the input is unusual.
Most bugs in string-parsing SQL do not come from the normal case. They come from a row where the delimiter is missing, a value is NULL, or a calculated position lands on 0. Oracle usually does not raise an error in these cases. It returns a quiet result such as NULL, 0, or the whole string, and that result then flows into the rest of your query.
Oracle treats the empty string as NULL
In Oracle, a zero-length VARCHAR2 value is the same thing as NULL. This differs from many other databases and it explains several results below.
SELECT CASE WHEN '' IS NULL THEN 'empty string is NULL' ELSE 'empty string is not NULL' END AS result,
LENGTH('') AS len_of_empty,
LENGTH('abc') AS len_of_abc
FROM dual;
-- result = 'empty string is NULL', len_of_empty = NULL, len_of_abc = 3Because of this, a function that "returns an empty string" actually returns NULL. A comparison such as WHERE SUBSTR(col, 1, 0) = '' never matches any row, because comparing anything to NULL is neither true nor false. Test for the result with IS NULL.
SUBSTR edge cases
SUBSTR(string, position [, length]) has four situations that surprise people.
SELECT SUBSTR('abc', 0, 2) AS pos_zero,
SUBSTR('abc', 5) AS past_end,
SUBSTR('abc', 1, 0) AS zero_len,
SUBSTR('abc', 1, -1) AS negative_len
FROM dual;
-- pos_zero = 'ab', past_end = NULL, zero_len = NULL, negative_len = NULL- Position 0 is treated as position 1.
SUBSTR('abc', 0, 2)returns'ab', the same as starting at 1. It does not shift the window left. - A start position past the end returns NULL, not an empty-looking error.
- A length of 0 or less returns NULL.
- A negative start before the first character also returns NULL.
SUBSTR('abc', -5)asks to start two characters before the string begins, and Oracle does not clip the request to fit.
A NULL in any argument makes the result NULL:
SELECT SUBSTR(NULL, 1, 2) AS null_string,
SUBSTR('abc', NULL) AS null_position,
SUBSTR('abc', 1, NULL) AS null_length
FROM dual;
-- all three results are NULLThe last case matters in practice. If the length is computed from another function that can return NULL, the whole SUBSTR becomes NULL, which can hide the real problem.
INSTR edge cases
INSTR(string, substring [, position [, occurrence]]) signals "not found" with the number 0 instead of NULL. That is a valid number, so it passes through arithmetic without any warning.
SELECT INSTR('abc', 'z') AS no_match,
INSTR('abc', 'B') AS wrong_case,
INSTR(NULL, 'a') AS null_string,
INSTR('abc', NULL) AS null_search
FROM dual;
-- no_match = 0, wrong_case = 0, null_string = NULL, null_search = NULLMatching is case-sensitive, so 'B' does not find 'b'. To search without regard to case, apply UPPER or LOWER to both sides: INSTR(UPPER(col), 'B').
An occurrence below 1 is one of the few places where these functions raise an error:
SELECT INSTR('a,b,c', ',', 1, 0) AS bad_occurrence
FROM dual;
-- ORA-01428: argument '0' is out of rangeAsking for an occurrence that does not exist, such as the fifth comma in 'a,b,c', is not an error. It returns 0.
How "no match" propagates
The most common real-world failure is feeding an INSTR result of 0 into SUBSTR. Take the email parsing pattern from earlier chapters and run it on a value that has no @:
SELECT email,
SUBSTR(email, 1, INSTR(email, '@') - 1) AS username,
SUBSTR(email, INSTR(email, '@') + 1) AS domain
FROM (SELECT '[email protected]' AS email FROM dual
UNION ALL
SELECT 'no-at-sign' FROM dual);
-- row 1: username = 'user', domain = 'example.com'
-- row 2: username = NULL, domain = 'no-at-sign'For the second row, INSTR returns 0. The username expression becomes SUBSTR(email, 1, -1), and a negative length returns NULL. The domain expression becomes SUBSTR(email, 1), which returns the whole string. The domain column now contains a value that is not a domain, and nothing flags it. One column fails with NULL and the other fails with plausible-looking text.
The fix is to test the position before using it:
SELECT email,
CASE WHEN INSTR(email, '@') > 0
THEN SUBSTR(email, 1, INSTR(email, '@') - 1)
END AS username,
CASE WHEN INSTR(email, '@') > 0
THEN SUBSTR(email, INSTR(email, '@') + 1)
END AS domain
FROM (SELECT '[email protected]' AS email FROM dual
UNION ALL
SELECT 'no-at-sign' FROM dual);
-- row 2: username = NULL, domain = NULLA CASE without an ELSE returns NULL when the condition is false, so rows with no delimiter produce NULL in both columns. That is an honest "could not parse" signal.
REPLACE edge cases
REPLACE(string, search [, replacement]) is the most forgiving of the three, but it has its own rules.
SELECT REPLACE('abc', 'b', NULL) AS null_replacement,
REPLACE('abc', NULL, 'x') AS null_search,
REPLACE(NULL, 'b', 'x') AS null_string,
REPLACE('abc', 'z', 'x') AS no_match
FROM dual;
-- null_replacement = 'ac', null_search = 'abc', null_string = NULL, no_match = 'abc'- A NULL or omitted replacement deletes each match. This is why
REPLACE(phone, '-')removes hyphens. - A NULL search string is not an error and not a deletion. The original string comes back unchanged.
- A NULL string returns NULL.
- No match returns the original string, so
REPLACEis safe to run on every row.
Matches are found from left to right and do not overlap, and REPLACE does not rescan its own output:
SELECT REPLACE('aaa', 'aa', 'b') AS non_overlapping
FROM dual;
-- non_overlapping = 'ba'The first two a characters become b, and the third a has no partner, so it stays.
A character you forgot to list stays
With nested REPLACE calls, each call handles exactly one search string. Anything you do not list survives.
SELECT REPLACE(REPLACE(REPLACE('(555) 123-4567', '(', ''), ')', ''), ' ', '') AS cleaned
FROM dual;
-- cleaned = '555123-4567' (the '-' remains)Add a fourth REPLACE for the hyphen, or use TRANSLATE or REGEXP_REPLACE when the list of unwanted characters grows. Those are covered in a later chapter.
Summary of results
| Call | Result | Reason |
|---|---|---|
| `SUBSTR('abc', 0, 2)` | `'ab'` | Position 0 acts as 1 |
| `SUBSTR('abc', 5)` | NULL | Start is past the end |
| `SUBSTR('abc', 1, 0)` | NULL | Length below 1 |
| `SUBSTR('abc', -5)` | NULL | Start is before the first character |
| `SUBSTR(NULL, 1, 2)` | NULL | NULL argument |
| `INSTR('abc', 'z')` | 0 | No match is 0, not NULL |
| `INSTR('abc', NULL)` | NULL | NULL argument |
| `INSTR('a,b', ',', 1, 0)` | ORA-01428 | Occurrence must be 1 or more |
| `REPLACE('abc', 'b', NULL)` | `'ac'` | NULL replacement deletes |
| `REPLACE('abc', NULL, 'x')` | `'abc'` | NULL search changes nothing |
Handling NULL results on purpose
Once you know a function can return NULL, decide what the NULL should become. NVL(expr, default) and COALESCE substitute a value, and || concatenation treats NULL as an empty string:
SELECT 'Domain: ' || SUBSTR('no-at-sign', INSTR('no-at-sign', '@') + 2) AS label,
NVL(SUBSTR('abc', 5), 'n/a') AS with_default
FROM dual;
-- label = 'Domain: ', with_default = 'n/a'In the first column, INSTR returns 0, the start becomes 2, and SUBSTR('no-at-sign', 2) would normally return text. The point of the example is the second column, where NVL replaces a NULL result with a visible default. Use a default only when a placeholder is better than NULL for the consumer of the data. For data cleaning, keeping NULL is often the correct signal.
Checking edge cases before you ship
Build a small set of hostile rows and run your expression against all of them. A useful set has these cases:
- A normal value that has the delimiter once.
- A value with no delimiter.
- A value with the delimiter at the first position.
- A value with the delimiter at the last position.
- A value with the delimiter repeated.
- A NULL value.
WITH samples AS (
SELECT 'a,b' AS s FROM dual UNION ALL
SELECT 'ab' FROM dual UNION ALL
SELECT ',ab' FROM dual UNION ALL
SELECT 'ab,' FROM dual UNION ALL
SELECT 'a,b,c' FROM dual UNION ALL
SELECT NULL FROM dual
)
SELECT s,
INSTR(s, ',') AS comma_pos,
CASE WHEN INSTR(s, ',') > 0
THEN SUBSTR(s, 1, INSTR(s, ',') - 1) END AS before_comma,
CASE WHEN INSTR(s, ',') > 0
THEN SUBSTR(s, INSTR(s, ',') + 1) END AS after_comma
FROM samples;Note what happens for ',ab'. The comma is at position 1, so the length passed to SUBSTR is 0, and the "before" part is NULL. For 'ab,', the "after" part starts past the end of the string and is also NULL. Both are correct, but they look identical to the "no delimiter" case unless you also look at comma_pos. If your downstream code must tell these apart, keep the position as its own column.
Exercise
What does each expression return? (a) SUBSTR('Oracle', 0, 3) (b) SUBSTR('Oracle', 3, 0) (c) INSTR('Oracle', 'x') + 1 (d) REPLACE('banana', 'ana', 'X')
Show answer
(a) 'Ora', because position 0 is treated as 1. (b) NULL, because a length below 1 returns NULL. (c) 1, because INSTR returns 0 for no match and 0 + 1 is 1. (d) 'bXna', because the first 'ana' at position 2 is replaced and matching continues after it, so the final 'a' is not part of a second match.
Exercise
A table has a column path holding values like 'docs/report.pdf' and some values with no slash, such as 'readme'. The query SUBSTR(path, INSTR(path, '/', -1) + 1) returns 'readme' for the second kind of row. Why, and how would you make it return NULL instead?
Show answer
With no slash, INSTR returns 0, so the start position is 1 and SUBSTR returns the whole string. Guard it: CASE WHEN INSTR(path, '/', -1) > 0 THEN SUBSTR(path, INSTR(path, '/', -1) + 1) END. The CASE has no ELSE, so rows without a slash produce NULL.
Exercise
Why does SELECT * FROM t WHERE SUBSTR(code, 1, 0) = '' return no rows, even though SUBSTR(code, 1, 0) is "empty" for every row?
Show answer
Oracle treats an empty string as NULL, and SUBSTR with a length of 0 returns NULL. Comparing NULL to NULL with = is never true, so no row matches. Use WHERE SUBSTR(code, 1, 0) IS NULL, which matches every row whose code is not itself causing another NULL result.