Sub topic 2
REPLACE: substituting and removing text
This chapter assumes you know basic SELECT statements, the WHERE clause, VARCHAR2 strings, and the DUAL table. It also assumes you know the basic SUBSTR and INSTR signatures.
Substituting and removing text with REPLACE
REPLACE(string, search, replacement) finds every occurrence of search and swaps in replacement. If you omit the third argument, the matches are removed.
SELECT REPLACE('2026-11-28', '-', '/') AS slashed,
REPLACE('555-123-4567', '-') AS digits_only
FROM dual;
-- slashed = '2026/11/28', digits_only = '5551234567'Counting from the end with negative positions
A negative start position in SUBSTR counts backward from the end of the string. The extraction still reads left to right.
SELECT SUBSTR('Oracle Database', -8) AS last_eight,
SUBSTR('Oracle Database', -8, 4) AS middle
FROM dual;
-- last_eight = 'Database', middle = 'Data'INSTR with a start position, an occurrence, and backward search
INSTR(string, search, start, occurrence) returns the 1-based position of a match, or 0 when nothing matches. The start position sets where the search begins, and the occurrence picks which match to return. A negative start searches backward from the end.
| Argument | Meaning |
|---|---|
| start | Position to begin searching; a negative value searches backward |
| occurrence | Which match to return; 1 is the first |
SELECT INSTR('a,b,c,d', ',', 1, 2) AS second_comma,
INSTR('a,b,c,d', ',', -1) AS last_comma
FROM dual;
-- second_comma = 4, last_comma = 6Splitting strings by combining SUBSTR and INSTR
Use INSTR to find a delimiter, then pass that position to SUBSTR to cut the string.
SELECT SUBSTR(email, 1, INSTR(email, '@') - 1) AS username,
SUBSTR(email, INSTR(email, '@') + 1) AS domain
FROM (SELECT '[email protected]' AS email FROM dual);
-- username = 'user', domain = 'example.com'To find a file extension, search backward for the last dot:
SELECT SUBSTR('report.final.pdf', INSTR('report.final.pdf', '.', -1) + 1) AS extension
FROM dual;
-- extension = 'pdf'Exercise
What does REPLACE('a-b-c', '-') return?
Show answer
'abc'. Omitting the replacement argument removes every match.