Sub topic 1
Working with strings in Oracle: positions and NULLs
SUBSTR, INSTR and REPLACE all work with character positions and all treat NULL in particular ways. This chapter covers both ideas before the later chapters use the three functions in detail. Most mistakes with these functions come from an off-by-one position or an unexpected NULL.
Prerequisites
This chapter assumes you can already do the following:
- Write a basic
SELECTstatement with aWHEREclause. - Recognize
VARCHAR2columns and write string literals in single quotes. - Use the
DUALtable to try out an expression without a real table. - Explain in general terms what NULL means in SQL: a missing or unknown value.
You need an Oracle session such as SQL*Plus, SQL Developer or SQLcl. Every example runs as shown.
How Oracle numbers the characters in a string
Oracle counts character positions starting at 1, not 0. The first character is at position 1, the second at position 2, and so on. The same numbering applies in SUBSTR, INSTR and every other function in this tutorial.
For the string Oracle:
| Position | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| Character | O | r | a | c | l | e |
Position is a different idea from length. LENGTH returns how many characters a string has, and the last character sits at the position equal to that length.
SELECT LENGTH('Oracle') AS len,
SUBSTR('Oracle', 1, 1) AS first_char,
SUBSTR('Oracle', 6, 1) AS last_char,
INSTR('Oracle', 'c') AS c_position
FROM dual;
-- len = 6, first_char = 'O', last_char = 'e', c_position = 4Four things to note about this query:
SUBSTR('Oracle', 6, 1)means "start at position 6 and take 1 character".INSTRreports a position in the same 1-based numbering. Thecis the fourth character, so the answer is 4.- Because both functions share one numbering scheme, you can pass the result of
INSTRstraight intoSUBSTR. Later chapters do this to split strings. - Spaces count as characters. In
'a b', thebis at position 3.
Many other languages count from 0, so a position copied from Python, Java or JavaScript will be one too low in Oracle.
What the three functions do
| Function | Question it answers | Returns |
|---|---|---|
| `SUBSTR(string, start [, length])` | What text is at this position? | A string |
| `INSTR(string, search [, start [, occurrence]])` | At what position does this text begin? | A number, 0 if not found |
| `REPLACE(string, search [, replacement])` | What does the string look like with this text swapped? | A string |
SUBSTR and REPLACE return text. INSTR returns a number. That number is a position, never text, and INSTR does not change the string.
SELECT SUBSTR('Oracle Database', 1, 6) AS part,
INSTR('Oracle Database', 'Data') AS pos,
REPLACE('Oracle Database', 'Oracle', 'Big') AS swapped
FROM dual;
-- part = 'Oracle', pos = 8, swapped = 'Big Database'All three are case-sensitive. INSTR('Oracle', 'o') returns 0 because the string has an uppercase O, not a lowercase o. To ignore case, wrap the input in UPPER or LOWER:
SELECT INSTR('Oracle', 'o') AS exact_case,
INSTR(LOWER('Oracle'), 'o') AS ignore_case
FROM dual;
-- exact_case = 0, ignore_case = 1NULL and the empty string
NULL means "no value". In Oracle, an empty string is also NULL. This is the largest difference from databases such as PostgreSQL or SQL Server, where '' is a real, zero-length string.
SELECT CASE WHEN '' IS NULL
THEN 'empty string is NULL'
ELSE 'empty string is a value'
END AS test
FROM dual;
-- test = 'empty string is NULL'Three consequences follow directly.
LENGTH('')is NULL, not 0. An empty value has no length because it has no value.- You cannot test for NULL with
=. The comparisonx = NULLis neither true nor false but unknown, so aWHEREclause never keeps the row. UseIS NULLorIS NOT NULL. - A column set to
''is stored as NULL. If you insert an empty string, you later find it withIS NULL, not= ''.
SELECT LENGTH('') AS empty_len FROM dual;
-- empty_len = NULL
SELECT COUNT(*) AS eq_count FROM dual WHERE NULL = NULL;
-- eq_count = 0
SELECT COUNT(*) AS is_count FROM dual WHERE NULL IS NULL;
-- is_count = 1The concatenation operator || is one exception to NULL spreading. It treats NULL as an empty string, so it does not make the whole result NULL:
SELECT 'abc' || NULL || 'def' AS joined FROM dual;
-- joined = 'abcdef'How NULL moves through SUBSTR, INSTR and REPLACE
The rule for SUBSTR and INSTR is simple: if any argument is NULL, the result is NULL. That includes the position and length arguments, not only the string.
SELECT SUBSTR(NULL, 1, 2) AS substr_null_string,
SUBSTR('abc', NULL) AS substr_null_start,
INSTR(NULL, 'a') AS instr_null_string,
INSTR('abc', NULL) AS instr_null_search,
INSTR('abc', 'b', NULL) AS instr_null_start
FROM dual;
-- every column is NULLREPLACE has special rules for its second and third arguments:
| Call | Result | Reason |
|---|---|---|
| `REPLACE(NULL, 'a', 'b')` | NULL | The input string is NULL |
| `REPLACE('banana', NULL, 'x')` | `'banana'` | A NULL search string matches nothing, so the string is unchanged |
| `REPLACE('banana', 'a', NULL)` | `'bnn'` | A NULL replacement removes each match |
| `REPLACE('banana', 'a')` | `'bnn'` | Leaving out the replacement does the same |
The last two rows matter when the replacement comes from a column. If that column is NULL for some rows, those rows lose the matched text instead of keeping it. Wrap the replacement in NVL or COALESCE when that is not what you want.
Handling NULL in a table
NULLs normally come from table data. This query builds a small contact list in a WITH clause so you do not need to create a table:
WITH contacts (id, name, phone) AS (
SELECT 1, 'Ada', '555-0101' FROM dual UNION ALL
SELECT 2, 'Lin', NULL FROM dual UNION ALL
SELECT 3, 'Raj', '' FROM dual
)
SELECT id,
name,
SUBSTR(phone, 1, 3) AS area,
COALESCE(SUBSTR(phone, 1, 3), 'n/a') AS area_safe
FROM contacts
ORDER BY id;
-- id 1: area = '555', area_safe = '555'
-- id 2: area = NULL, area_safe = 'n/a'
-- id 3: area = NULL, area_safe = 'n/a'Row 3 shows the empty-string rule at work. The phone value '' was stored as NULL, so it behaves exactly like row 2. COALESCE returns its first non-NULL argument and gives you a default when the string function returns NULL.
Fixed-length strings and implicit conversion
Two other behaviors change what positions and lengths mean.
CHAR pads with spaces
A CHAR(n) column or value is blank-padded to exactly n characters. A VARCHAR2 value is stored as given.
SELECT LENGTH(CAST('ab' AS CHAR(5))) AS char_len,
LENGTH(CAST('ab' AS VARCHAR2(5))) AS varchar2_len
FROM dual;
-- char_len = 5, varchar2_len = 2The padding spaces are real characters, and INSTR and SUBSTR see them. If a table uses CHAR columns, pattern-matching positions may include trailing spaces. Use VARCHAR2 for new columns, or apply RTRIM to the CHAR value before parsing it.
Numbers and dates become strings implicitly
If you pass a number to a string function, Oracle converts it to text first:
SELECT SUBSTR(12345, 2, 3) AS digits FROM dual;
-- digits = '234'This works, but it is risky for dates. The text form of a date depends on the session setting NLS_DATE_FORMAT, so SUBSTR(SYSDATE, 1, 9) can return different text on different sessions. Convert explicitly with TO_CHAR(value, format) and then take a part of the result:
SELECT SUBSTR(TO_CHAR(DATE '2026-11-28', 'YYYY-MM-DD'), 6, 2) AS month_part
FROM dual;
-- month_part = '11'If you only need the month, TO_CHAR(date, 'MM') is simpler. Reserve SUBSTR for text that is already a string.
Common mistakes in this area
- Using 0-based positions. The first character is at position 1.
- Testing
column = ''. This never matches anything. Usecolumn IS NULL. - Treating an
INSTRresult of 0 as a valid position. Zero means "not found". Feeding it intoSUBSTRarithmetic produces wrong text without raising an error. - Forgetting case sensitivity.
INSTRandREPLACEdo not match across upper and lower case. - Expecting
||andSUBSTRto treat NULL the same way.||skips NULL, whileSUBSTRreturns NULL. - Parsing
CHARcolumns without trimming. Trailing padding gets counted.
Quick reference
- Positions start at 1.
INSTRreturns a number: a position, or 0 for "not found".''is NULL, soLENGTH('')is NULL and= ''never matches.SUBSTRandINSTRreturn NULL if any argument is NULL.REPLACEwith a NULL search string returns the input unchanged. A NULL replacement removes the matches.||treats NULL as an empty string.
Exercise
Without running it, predict the value of each column. Then explain why the result in column c differs from the one in column d.
SELECT INSTR('Oracle', 'a') AS a,
SUBSTR('Oracle', INSTR('Oracle', 'a'), 2) AS b,
REPLACE('Oracle', 'x', NULL) AS c,
REPLACE('Oracle', NULL, 'x') AS d
FROM dual;
Show answer
a = 3, because a is the third character of Oracle. b = 'ac', because SUBSTR starts at position 3 and takes 2 characters. c = 'Oracle': the search text x does not appear, so there is nothing to remove, and a NULL replacement only removes matches. d = 'Oracle': a NULL search string matches nothing, so the input is returned unchanged. The two columns happen to have the same value. The difference is the reason: in c nothing was found, and in d nothing could be searched for. If the search text had been r in c, the result would have been 'Oacle'.
Exercise
A table column middle_name holds NULL for people without a middle name, and some rows were loaded with an empty string. You write WHERE middle_name = '' to find them. How many rows does the query return, and what is the correct filter? Then write an expression that returns the first letter of middle_name, or the text none when there is no middle name.
Show answer
The query returns 0 rows, because an empty string is NULL in Oracle and = NULL is never true. The correct filter is WHERE middle_name IS NULL, which finds both the original NULL rows and the rows loaded with ''. The expression is COALESCE(SUBSTR(middle_name, 1, 1), 'none'). SUBSTR returns NULL for a NULL input, and COALESCE then supplies the default.