Sub topic 2
SUBSTR: extracting part of a string
This chapter covers SUBSTR, the Oracle function that cuts a piece out of a string by position. It assumes you can write basic SELECT statements with a WHERE clause, know VARCHAR2 and string literals, have used the DUAL table, and know that NULL means "no value" in SQL. Earlier chapters covered positions and NULL handling in general. Here we look closely at how SUBSTR reads its arguments, so you can predict its output without running it.
The signature
SUBSTR(char, position [, substring_length])charis the source string. It can be a literal, a column, or any expression that produces a string.positionis where extraction starts. Counting starts at 1, not 0.substring_lengthis how many characters to return. If you leave it out,SUBSTRreturns everything frompositionto the end of the string.
The result is the same kind of string as the input. A VARCHAR2 input gives a VARCHAR2, and a CLOB input gives a CLOB.
Basic extraction
SELECT SUBSTR('Oracle Database', 1, 6) AS first_word,
SUBSTR('Oracle Database', 8) AS rest
FROM dual;
-- first_word = 'Oracle', rest = 'Database'The first call starts at character 1 and takes 6 characters. The second starts at character 8, the D of Database, and has no length, so it runs to the end. Spaces count as characters, which is why Database starts at 8 and not 7.
This is the right tool when the layout is fixed, meaning each piece always sits at the same position. Product codes are a typical case:
SELECT SUBSTR(code, 1, 2) AS region,
SUBSTR(code, 4, 4) AS year_part,
SUBSTR(code, -5) AS serial
FROM (SELECT 'EU-2026-00417' AS code FROM dual);
-- region = 'EU', year_part = '2026', serial = '00417'The -5 in the last column is a negative position, covered next.
Negative positions
A negative position counts backward from the end of the string. -1 is the last character, -2 the second to last, and so on. Oracle converts that to a starting point and then reads left to right as usual.
SELECT SUBSTR('Oracle Database', -8) AS last_eight,
SUBSTR('Oracle Database', -8, 4) AS middle
FROM dual;
-- last_eight = 'Database', middle = 'Data'The string has 15 characters, so -8 points at character 8. From there, SUBSTR takes 8 characters, or 4 when you give a length. The length never reverses the direction. SUBSTR('Oracle Database', -8, 4) returns Data, not the four characters before position 8.
The diagram shows how Oracle turns a position value into a starting point.
Negative positions are useful when the end of the string is stable and the start is not. Two examples are the last four digits of a card number and the last two characters of a country code suffix:
SELECT SUBSTR('4111111111111111', -4) AS last4
FROM dual;
-- last4 = '1111'What happens when the length is too long
If substring_length asks for more characters than remain, SUBSTR returns what is left. It does not raise an error and does not pad the result.
SELECT SUBSTR('abc', 2, 100) AS short_result
FROM dual;
-- short_result = 'bc'This lets you write "from position 2 to the end, at most 100 characters" without first checking the string length. It also means you cannot detect truncation from the result alone. If you need that, compare the result's LENGTH with the length you asked for.
Edge cases
Most surprises with SUBSTR come from a small set of rules.
SELECT SUBSTR('abc', 0, 2) AS pos_zero,
SUBSTR('abc', 5) AS past_end,
SUBSTR('abc', 1, 0) AS zero_len
FROM dual;
-- pos_zero = 'ab', past_end = NULL, zero_len = NULL| Call | Result | Rule |
|---|---|---|
| `SUBSTR('abc', 0, 2)` | `ab` | Position 0 is treated as 1. |
| `SUBSTR('abc', 5)` | NULL | The start is past the end of the string. |
| `SUBSTR('abc', 1, 0)` | NULL | A length below 1 returns NULL. |
| `SUBSTR('abc', 1, -1)` | NULL | A negative length also returns NULL. |
| `SUBSTR('abc', -5)` | NULL | A negative position reaching before the first character returns NULL. |
| `SUBSTR(NULL, 1, 2)` | NULL | A NULL string gives NULL. |
| `SUBSTR('abc', NULL)` | NULL | A NULL position or length gives NULL. |
Two of these rules differ from other languages and SQL dialects:
- A zero-length result is NULL, not an empty string. Oracle treats an empty string as NULL, so the two are the same thing. In many other languages
substring("abc", 0, 0)returns"". - A position of 0 is accepted and means 1. Other databases may treat position 0 differently, so check this when porting SQL from them.
Because an empty string is NULL, SUBSTR('', 1) also returns NULL. If you add SUBSTR results to a larger string, NULLs are harmless with ||, which treats NULL as an empty string. With a function that propagates NULL, or in a comparison, a NULL result can drop rows silently.
A quick way to see all of these as visible text is to wrap each call in NVL:
SELECT NVL(SUBSTR('abc', 5), '<NULL>') AS past_end,
NVL(SUBSTR('abc', 1, 0), '<NULL>') AS zero_len,
NVL(SUBSTR('abc', -5), '<NULL>') AS too_far_back
FROM dual;
-- past_end = '<NULL>', zero_len = '<NULL>', too_far_back = '<NULL>'Using SUBSTR with columns
Applied to a table, SUBSTR runs once per row. The common pattern is to cut a fixed-width field out of a column. This example uses an inline view so it runs without creating a table.
WITH people AS (
SELECT 'alice' AS first_name FROM dual UNION ALL
SELECT 'BOB' FROM dual UNION ALL
SELECT 'cHARLIE' FROM dual
)
SELECT first_name,
UPPER(SUBSTR(first_name, 1, 1)) || LOWER(SUBSTR(first_name, 2)) AS tidy
FROM people;
-- Alice, Bob, CharlieThe first SUBSTR takes one character and the second takes the rest. Both use position arithmetic only, with no search involved. INITCAP does this more directly for single words, but the two-part form shows how SUBSTR pieces fit back together.
Gotchas with data types
SUBSTR expects a string. If you pass something else, Oracle converts it implicitly, and the result may not be what you expect.
- Numbers.
SUBSTR(12345, 2, 3)converts 12345 to the text'12345'and returns'234'. This works, but the conversion uses default number formatting. For decimals or large values the text may not look like what you assumed. UseTO_CHAR(n, 'format')first when the layout matters. - Dates.
SUBSTR(hire_date, 1, 9)converts the date using the session'sNLS_DATE_FORMAT. Two sessions with different settings can return different results from the same query. Convert explicitly withTO_CHAR(hire_date, 'YYYY-MM-DD')and then take the piece you need. - CHAR columns. A
CHAR(10)column holding'abc'is stored as'abc ', padded with blanks.SUBSTR(col, -3)returns three spaces, not'abc'. UseRTRIMfirst, or store the value inVARCHAR2. - Fractional arguments. Position and length are converted to integers. Pass whole numbers, because relying on how a fraction is converted makes the code hard to read.
Using SUBSTR in a WHERE clause
You can filter on a substring just like on a column:
SELECT code
FROM (SELECT 'EU-2026-00417' AS code FROM dual
UNION ALL
SELECT 'US-2026-00018' FROM dual)
WHERE SUBSTR(code, 1, 2) = 'EU';
-- EU-2026-00417An index on code cannot be used for this predicate, because the function is applied to the column. If the query is frequent and the table is large, either use LIKE 'EU%', which can use an ordinary index, or create a function-based index on SUBSTR(code, 1, 2). The expression in the query must match the index definition exactly. A later chapter covers this together with UPDATE and ORDER BY.
Common mistakes
- Counting from 0.
SUBSTR('Oracle', 0, 3)returns'Ora'only because position 0 is silently treated as 1.SUBSTR('Oracle', 1, 3)is the correct and clearer form. Code that mixes the two can be off by one when a start position is calculated. - Confusing length with end position. The third argument is how many characters to take, not where to stop. To take characters 3 through 6, write
SUBSTR(s, 3, 4), since 6 - 3 + 1 = 4. - Assuming a missing piece gives an empty string. The result is NULL. Test with
IS NULL, not= '', because comparing anything to''is never true in Oracle. - Ignoring spaces. A leading or trailing space shifts every position. If the source data is dirty, apply
TRIMbeforeSUBSTR. - Hard-coding positions for variable-length data. If the piece you want is not at a fixed place, you need to find where it starts first. That is the job of
INSTR, introduced in the next chapter.
Summary of rules
- Positions start at 1. Position 0 is treated as 1.
- A negative position counts back from the end, and extraction still goes left to right.
- Omitting the length returns everything to the end of the string.
- A length longer than the remainder returns what is left.
- A length below 1, a start past the end, a NULL argument, or an empty string all give NULL.
Exercise
The column ref contains the value 'INV-2026-000731'. Write a query on DUAL that returns three columns: the prefix 'INV', the year '2026', and the last three characters '731'. Use only SUBSTR with literal positions.
Show answer
SELECT SUBSTR(ref, 1, 3) AS prefix, SUBSTR(ref, 5, 4) AS year_part, SUBSTR(ref, -3) AS last3 FROM (SELECT 'INV-2026-000731' AS ref FROM dual); The prefix is characters 1 to 3. The year starts at position 5, after 'INV-', and is 4 characters long. A start of -3 counts back from the end and, with no length, returns the final three characters.
Exercise
Predict the result of each call, writing NULL where applicable: (a) SUBSTR('Oracle', 0, 3), (b) SUBSTR('Oracle', 4, 10), (c) SUBSTR('Oracle', -3, 2), (d) SUBSTR('Oracle', 7), (e) SUBSTR('Oracle', 2, -1).
Show answer
(a) 'Ora', because position 0 is treated as 1. (b) 'cle', because the length is cut off at the end of the string. (c) 'cl', because -3 points at the 4th character, 'c', and 2 characters are taken left to right. (d) NULL, because 'Oracle' has 6 characters and the start is past the end. (e) NULL, because a length below 1 returns NULL.
Exercise
A CHAR(8) column holds the value 'AB12'. Why does SUBSTR(col, -2) not return '12', and how do you fix it?
Show answer
A CHAR(8) value is padded with blanks to 8 characters, so it is stored as 'AB12 '. A start of -2 therefore returns two spaces. Apply RTRIM first, as in SUBSTR(RTRIM(col), -2), which returns '12', or store the data in a VARCHAR2 column.