Sub topic 5
Counting from the end with negative positions
This chapter covers how SUBSTR and INSTR treat a negative position. It assumes you can write a basic SELECT with a WHERE clause and know VARCHAR2, string literals, the DUAL table and the idea of NULL. It also assumes you have used SUBSTR(string, start, length) with positive positions and know that INSTR returns a 1-based position, or 0 when nothing matches.
How a negative start position works
Normally SUBSTR counts from the left, and the first character is position 1. A negative start position makes it count from the right. Position -1 is the last character, -2 is the second to last, and so on.
Oracle converts a negative start to an ordinary left-based position:
left_position = LENGTH(string) + start + 1For 'Oracle Database', which has 15 characters, a start of -8 becomes 15 + (-8) + 1 = 8. Position 8 is the D of Database.
SELECT SUBSTR('Oracle Database', -8) AS last_eight,
SUBSTR('Oracle Database', -8, 4) AS middle
FROM dual;
-- last_eight = 'Database', middle = 'Data'The direction of extraction never changes. A negative start only picks the starting point. The characters are still read from left to right, so the length argument takes characters to the right of the starting point.
A reference table
This table uses 'Oracle Database' (15 characters):
| Call | Converted position | Result |
|---|---|---|
| `SUBSTR(s, -1)` | 15 | `e` |
| `SUBSTR(s, -4)` | 12 | `base` |
| `SUBSTR(s, -8, 4)` | 8 | `Data` |
| `SUBSTR(s, -15)` | 1 | `Oracle Database` |
| `SUBSTR(s, -16)` | 0 or less | `NULL` |
You can reproduce every row with one query:
WITH t AS (SELECT 'Oracle Database' AS s FROM dual)
SELECT SUBSTR(s, -1) AS minus_1,
SUBSTR(s, -4) AS minus_4,
SUBSTR(s, -8, 4) AS minus_8_len_4,
SUBSTR(s, -15) AS minus_15,
SUBSTR(s, -16) AS minus_16
FROM t;The last column is NULL. A start that points before the first character returns NULL. It does not return the whole string and it does not raise an error.
Why negative positions are useful
A negative start is most useful when the part you want is defined by its distance from the end, and the total length varies. These strings differ in length, but the last two characters are always the day:
SELECT d,
SUBSTR(d, -2) AS day_part,
SUBSTR(d, -5, 2) AS month_part
FROM (SELECT '2026-11-28' AS d FROM dual
UNION ALL
SELECT '2026-1-5' FROM dual);The first row gives 28 and 11. The second row has no zero padding, so the positions shift. SUBSTR('2026-1-5', -2) returns -5, and SUBSTR('2026-1-5', -5, 2) returns 6-. A negative start fixes the offset from the end only. If the characters before it can change length, you still need a delimiter search, which is covered below.
The same technique works for the last four digits of an identifier of any length:
SELECT SUBSTR('5551234567', -4) AS tail_10,
SUBSTR('12345678', -4) AS tail_8
FROM dual;
-- tail_10 = '4567', tail_8 = '5678'A positive-position version needs LENGTH to do the same thing: SUBSTR(s, LENGTH(s) - 3). The negative form is shorter, and it also handles NULL input without extra work, because SUBSTR(NULL, -4) is simply NULL.
Negative start combined with a length
The length counts rightward from the converted start. It cannot reach past the end of the string. If you ask for more characters than remain, you get only what remains:
SELECT SUBSTR('Oracle Database', -3, 10) AS short_result
FROM dual;
-- short_result = 'ase'Only three characters lie at or after position 13, so the result has three characters even though the length argument was 10. Do not expect the extraction to wrap around or to count back toward the left.
A negative length is a different matter. It never means "count leftward." It returns NULL:
SELECT SUBSTR('Oracle Database', 3, -2) AS neg_length,
SUBSTR('Oracle Database', -8, -2) AS neg_both
FROM dual;
-- both results are NULLTo drop characters from the end, calculate a positive length instead:
SELECT SUBSTR('report.pdf', 1, LENGTH('report.pdf') - 4) AS base_name
FROM dual;
-- base_name = 'report'This approach works only if the suffix length is fixed. For variable suffixes, use the backward INSTR pattern in the next section.
Backward INSTR as the partner of SUBSTR
INSTR also accepts a negative start position. It then searches backward from that point toward the beginning of the string. A -1 starts the search at the last character, so the first match found is the last occurrence in the string.
The value INSTR returns is always an ordinary left-based position, even for a backward search. That is why its result plugs straight into a positive SUBSTR start. Here is the extension example from the plan:
SELECT SUBSTR('report.final.pdf', INSTR('report.final.pdf', '.', -1) + 1) AS extension
FROM dual;
-- extension = 'pdf'The last dot is at position 13. Adding 1 moves past it, and SUBSTR returns everything from position 14 to the end.
The fourth argument of INSTR is the occurrence number. During a backward search, occurrences are counted from the right, so INSTR(s, ',', -1, 2) finds the second comma from the end:
SELECT INSTR('a,b,c,d', ',', -1) AS last_comma,
INSTR('a,b,c,d', ',', -1, 2) AS second_last_comma
FROM dual;
-- last_comma = 6, second_last_comma = 4Splitting a path into directory and file name
Backward INSTR suits paths, where the last separator is the one that matters:
WITH t AS (SELECT 'C:/data/reports/q3.csv' AS p FROM dual)
SELECT SUBSTR(p, 1, INSTR(p, '/', -1) - 1) AS directory,
SUBSTR(p, INSTR(p, '/', -1) + 1) AS file_name
FROM t;
-- directory = 'C:/data/reports', file_name = 'q3.csv'The last slash is at position 16. The directory is characters 1 through 15, and the file name is everything from position 17.
Now consider a path with no slash, such as 'q3.csv'. INSTR returns 0, so the two expressions behave differently:
SUBSTR(p, 0 + 1)isSUBSTR(p, 1), which returns the whole string. A bare file name is correctly treated as a file name.SUBSTR(p, 1, 0 - 1)has a length of -1, so it returnsNULL. A path with no directory part gives aNULLdirectory.
Both results are reasonable here, but only because of how the edge cases combine. Check this behavior deliberately instead of assuming it.
Pitfalls
Padding in CHAR values
CHAR columns and casts are blank-padded to their declared length. A negative start counts from the end of the padded value, so you may get only spaces:
SELECT '[' || SUBSTR(c, -4) || ']' AS raw_tail,
'[' || SUBSTR(RTRIM(c), -4) || ']' AS trimmed_tail
FROM (SELECT CAST('1234' AS CHAR(8)) AS c FROM dual);
-- raw_tail = '[ ]', trimmed_tail = '[1234]'Apply RTRIM first, or store the data as VARCHAR2. VARCHAR2 values that have trailing spaces typed into them have the same problem, because the spaces are part of the data.
Start before the first character
When LENGTH(s) + start + 1 is less than 1, the result is NULL, as in the reference table. If your strings can be shorter than the offset you are asking for, handle it explicitly:
SELECT s,
CASE WHEN LENGTH(s) >= 4 THEN SUBSTR(s, -4) ELSE s END AS safe_tail
FROM (SELECT 'abcdef' AS s FROM dual
UNION ALL
SELECT 'ab' FROM dual);
-- safe_tail = 'cdef' and 'ab'Mixing up the two directions
Two statements are easy to confuse:
- A negative start in
SUBSTRmoves the starting point to the right end, but extraction still runs left to right. - A negative start in
INSTRmakes the search itself run right to left.
The returned position is left-based in both cases.
Empty strings
Oracle treats an empty string as NULL. If the input has no characters, any call returns NULL, whatever the start position. Treat NULL and empty input as the same case in your logic.
Practice
Exercise
What does SELECT SUBSTR('Oracle Database', -4, 2) FROM dual return, and why?
Show answer
It returns 'ba'. The string has 15 characters, so a start of -4 converts to position 15 - 4 + 1 = 12, which is the 'b' of 'base'. Extraction runs left to right for 2 characters, giving 'ba'.
Exercise
A column holds paths such as '/home/ann/notes.v2.txt'. Write an expression that returns only the file extension ('txt'), and say what it returns for a value with no dot, such as '/home/ann/README'.
Show answer
SUBSTR(p, INSTR(p, '.', -1) + 1). INSTR with -1 finds the last dot, and adding 1 skips it. With no dot, INSTR returns 0, so the expression becomes SUBSTR(p, 1) and returns the whole path '/home/ann/README', not NULL or an empty value. If you want NULL for a missing extension, add a CASE that checks INSTR(p, '.', -1) > 0 (a stricter version also checks that the dot comes after the last slash).
Exercise
Why does SUBSTR('abc', -5) return NULL, and how would you write a version that returns 'abc' instead?
Show answer
The start converts to 3 - 5 + 1 = -1, which is before the first character, so SUBSTR returns NULL. A safe version is CASE WHEN LENGTH(s) >= 5 THEN SUBSTR(s, -5) ELSE s END, or COALESCE(SUBSTR(s, -5), s) when the string is not NULL. If s itself can be NULL, COALESCE also returns s, which is NULL, so the result is still NULL.