Sub topic 3
INSTR: finding where a substring starts
This chapter covers the basic form of INSTR, the Oracle function that tells you where one piece of text begins inside another. It assumes you can write a basic SELECT with a WHERE clause, know VARCHAR2 and string literals, and know that DUAL is a one-row table for testing expressions. It also assumes you know NULL means "unknown" in SQL. Earlier chapters introduced positions and SUBSTR. Here you learn what INSTR returns and what it does with missing matches, case, wildcards, and NULLs. The start position, occurrence, and backward-search arguments get their own chapter, so this one only previews them.
What INSTR returns
INSTR does not return text. It returns a number: the 1-based position of the first character of the first match. Position 1 is the first character of the string, as in SUBSTR. If the substring does not occur, INSTR returns 0.
The basic form is:
INSTR(string, substring)SELECT INSTR('[email protected]', '@') AS at_pos,
INSTR('[email protected]', '#') AS missing
FROM dual;
-- at_pos = 5, missing = 0The @ is the fifth character, so at_pos is 5. The # never appears, so missing is 0. Because positions start at 1, 0 can never be a real position, which is why Oracle uses it to mean "not found".
Searching for more than one character
The substring can be longer than one character. INSTR returns the position where the whole substring starts, not where it ends.
SELECT INSTR('Oracle Database', 'Data') AS data_pos
FROM dual;
-- data_pos = 8Oracle takes seven characters, including the space, so Data starts at position 8. To find where a match ends, add the length of the substring and subtract 1: INSTR(s, sub) + LENGTH(sub) - 1.
Spaces and punctuation count as ordinary characters. A search for a comma followed by a space finds that exact two-character sequence:
SELECT INSTR('Smith, John', ', ') AS sep_pos
FROM dual;
-- sep_pos = 6If the data sometimes has Smith,John with no space, this search returns 0 for those rows. Check how consistent your data is before you rely on a multi-character delimiter.
Matching rules
INSTR follows a few rules that surprise people who are used to other tools.
| Behavior | Example | Result |
|---|---|---|
| Case-sensitive | `INSTR('Oracle Database', 'database')` | 0 |
| First match only | `INSTR('a@[email protected]', '@')` | 2 |
| No wildcards | `INSTR('50% off', '%')` | 3 |
| Whole substring must match | `INSTR('banana', 'nab')` | 0 |
Case sensitivity
INSTR compares characters exactly. To ignore case, convert both sides to the same case first:
SELECT INSTR('Oracle Database', 'database') AS exact,
INSTR(UPPER('Oracle Database'), UPPER('database')) AS ignoring_case
FROM dual;
-- exact = 0, ignoring_case = 8Applying UPPER to both arguments is safer than applying it to one. If the search term comes from a bind variable, you can't be sure what case it arrives in.
No wildcards
In a LIKE condition, % and _ are wildcards. INSTR treats every character literally, so you can search for them directly with no ESCAPE clause:
SELECT INSTR('50% off', '%') AS percent_pos,
INSTR('a_b', '_') AS underscore_pos
FROM dual;
-- percent_pos = 3, underscore_pos = 2This makes INSTR a convenient choice when the text you are searching for may contain % or _.
First match only
When the substring occurs more than once, the two-argument form reports only the first occurrence:
SELECT INSTR('a,b,c,d', ',') AS first_comma
FROM dual;
-- first_comma = 2To get a later occurrence, or to search from the right, you need the optional arguments covered in the next chapter.
NULL and empty strings
If either argument is NULL, the result is NULL, not 0. This differs from "not found", and the difference matters in a WHERE clause.
SELECT INSTR(NULL, 'a') AS null_string,
INSTR('abc', NULL) AS null_search
FROM dual;
-- both results are NULLOracle treats an empty string as NULL. A search for '' therefore returns NULL, not 1:
SELECT INSTR('abc', '') AS empty_search
FROM dual;
-- empty_search = NULLChecking whether text contains a substring
Because INSTR returns 0 when nothing matches, comparing the result with 0 gives you a "contains" test. The comparison must be explicit. Oracle SQL has no way to use a number as a condition on its own:
WITH emails AS (
SELECT '[email protected]' AS email FROM dual UNION ALL
SELECT 'invalid.address' FROM dual UNION ALL
SELECT 'a@[email protected]' FROM dual UNION ALL
SELECT NULL FROM dual
)
SELECT email,
INSTR(email, '@') AS at_pos
FROM emails
WHERE INSTR(email, '@') > 0;
-- [email protected] | 5
-- a@[email protected] | 2The row invalid.address has at_pos 0 and is filtered out. The NULL row gives INSTR a NULL result, so NULL > 0 is unknown and that row is filtered out as well.
The opposite test has a trap. To find rows that do not contain @, you might write INSTR(email, '@') = 0:
WITH emails AS (
SELECT '[email protected]' AS email FROM dual UNION ALL
SELECT 'invalid.address' FROM dual UNION ALL
SELECT NULL FROM dual
)
SELECT email
FROM emails
WHERE INSTR(email, '@') = 0;
-- invalid.addressThe NULL row is missing from the result. If you want rows with a NULL email too, say so explicitly:
WITH emails AS (
SELECT '[email protected]' AS email FROM dual UNION ALL
SELECT 'invalid.address' FROM dual UNION ALL
SELECT NULL FROM dual
)
SELECT email
FROM emails
WHERE INSTR(email, '@') = 0
OR email IS NULL;
-- invalid.address
-- (null)INSTR compared with LIKE
Both can test whether a column contains text. INSTR(col, 'x') > 0 and col LIKE '%x%' give the same answer for ordinary text.
| Point | `INSTR(col, 'x') > 0` | `col LIKE '%x%'` |
|---|---|---|
| Wildcard characters in the search term | Treated literally | Need `ESCAPE` |
| Returns the position | Yes | No |
| Index on `col` | Not usable | Not usable with a leading `%` |
Neither form can use a normal B-tree index on col when the pattern starts with % or when a function wraps the column. On a large table, a "contains" search is a full scan either way. Choose between them on readability and on whether you need the position.
Using the position
The position is most useful as input to other functions. SUBSTR takes a start position, so INSTR can tell it where to cut. The next chapters build on this, but one small example shows the idea:
SELECT SUBSTR(email, 1, INSTR(email, '@') - 1) AS username
FROM (SELECT '[email protected]' AS email FROM dual);
-- username = 'user'INSTR returns 5, so SUBSTR takes 4 characters starting at position 1. Notice what happens when the delimiter is missing: INSTR returns 0, the length becomes -1, and SUBSTR returns NULL. The result is not an error and not the whole string. Any code that splits a string with INSTR has to decide what to do with rows that have no delimiter.
A preview of the optional arguments
The full syntax adds two more arguments:
INSTR(string, substring [, position [, occurrence]])The third argument is where the search starts, and the fourth picks which match to return. For example:
SELECT INSTR('a,b,c,d', ',', 3) AS comma_from_3
FROM dual;
-- comma_from_3 = 4The search begins at position 3 (the b), skips the comma at position 2, and finds the one at position 4. The returned position is still counted from the start of the whole string, not from where the search began. The next chapter covers the occurrence argument and backward search with a negative position.
Common errors
- Treating 0 as a position. A result of 0 means "not found". Using it in
SUBSTRgives surprising results, and subtracting 1 from it gives a length of-1. - Expecting case-insensitive matching. Wrap both arguments in
UPPERorLOWER. - Testing
= 0and forgetting that NULL rows drop out. - Writing
WHERE INSTR(col, 'x')without a comparison. Oracle SQL raises an error because a number is not a condition. - Swapping the arguments. The string being searched comes first and the thing you are looking for comes second.
INSTR('@', '[email protected]')returns 0. - Searching for
''and expecting a position. The result is NULL.
Summary
INSTR(string, substring) returns the 1-based position of the first character of the first match. It returns 0 when there is no match and NULL when either argument is NULL, including an empty string. The match is case-sensitive and literal, with no wildcards. Comparing the result with 0 gives a contains test, but a NULL input needs separate handling. Position 0 and NULL both need attention before you pass the result to SUBSTR.
Exercise
What does SELECT INSTR('banana', 'na') FROM dual return, and what does SELECT INSTR('banana', 'NA') FROM dual return?
Show answer
The first query returns 3. The substring 'na' first starts at position 3 (b=1, a=2, n=3), and the later match at position 5 is ignored because only the first match is reported. The second query returns 0, because INSTR is case-sensitive and 'NA' does not occur in 'banana'.
Exercise
A table has a NOTES column. The query SELECT id FROM tickets WHERE INSTR(notes, 'urgent') = 0 should list every ticket whose notes do not mention "urgent", including tickets with no notes at all. Why does it miss the tickets where NOTES is NULL, and how do you fix it?
Show answer
When NOTES is NULL, INSTR returns NULL, and NULL = 0 evaluates to unknown, so the row is filtered out. Add an explicit check: WHERE INSTR(notes, 'urgent') = 0 OR notes IS NULL.
Exercise
Write a query that returns 'Smith, John' split into the position of the comma plus the number of characters in the last name, using only INSTR for the comma position. What are the two values?
Show answer
SELECT INSTR('Smith, John', ',') AS commapos, INSTR('Smith, John', ',') - 1 AS lastnamelength FROM dual; The comma is at position 6, so commapos = 6 and lastnamelength = 5, which is the length of 'Smith'.