Sub topic 4
REPLACE: substituting and removing text
REPLACE swaps every occurrence of one piece of text for another. If you leave out the replacement, it deletes the matches instead. This chapter assumes you can write a basic SELECT with a WHERE clause, you know VARCHAR2 and string literals, and you know that DUAL is Oracle's one-row helper table. It also assumes you know that Oracle treats an empty string as NULL. SUBSTR and INSTR work by position. REPLACE works by matching text, so it needs no position arithmetic.
Syntax and return value
REPLACE(char, search_string [, replacement_string])| Argument | Meaning |
|---|---|
| `char` | The source string to search. It can be `CHAR`, `VARCHAR2`, `NCHAR`, `NVARCHAR2`, `CLOB`, or `NCLOB`. |
| `search_string` | The text to look for. It can be one character or many. |
| `replacement_string` | The text to put in its place. If you omit it or pass `NULL`, the matches are removed. |
The result has the same data type family as char. REPLACE never changes the stored value. It returns a new string, and only an UPDATE writes that string back to a table.
Replacing and removing
The first query replaces every hyphen with a slash. The second leaves out the third argument, so the hyphens are deleted.
SELECT REPLACE('2026-11-28', '-', '/') AS slashed,
REPLACE('555-123-4567', '-') AS digits_only
FROM dual;
-- slashed = '2026/11/28', digits_only = '5551234567'Three behaviors matter here:
- All occurrences are replaced. There is no argument to limit it to the first match. To change only one occurrence, you need
SUBSTRandINSTR, orREGEXP_REPLACEwith an occurrence argument. - Removal is replacement with nothing. An omitted third argument, an explicit
NULL, and an empty string''all behave the same, because Oracle treats''asNULL. - The search string can be longer than one character.
REPLACE('one, two, three', ', ', ';')returnsone;two;three.
SELECT REPLACE('one, two, three', ', ', ';') AS joined,
REPLACE('one, two, three', ', ', NULL) AS explicit_null,
REPLACE('one, two, three', ', ', '') AS empty_literal
FROM dual;
-- joined = 'one;two;three'
-- explicit_null = 'onetwothree'
-- empty_literal = 'onetwothree'How REPLACE decides what to do
The function checks for NULL before it looks for any matches. A NULL source gives a NULL result. A NULL search string gives back the source unchanged.
One point surprises many people. A NULL replacement does not make the whole result NULL, which is how most Oracle functions treat NULL arguments. A NULL replacement means "delete the matches".
SELECT REPLACE(NULL, 'a', 'b') AS null_source,
REPLACE('abc', NULL, 'x') AS null_search,
REPLACE('abc', 'b', NULL) AS null_replacement
FROM dual;
-- null_source = NULL, null_search = 'abc', null_replacement = 'ac'Note that REPLACE('abc', '', 'x') also returns 'abc'. An empty search string does not insert x between every character, as it would in some other languages.
Matching rules
Case sensitivity
REPLACE compares characters exactly, so 'A' and 'a' are different.
SELECT REPLACE('Apple apple APPLE', 'apple', 'pear') AS result
FROM dual;
-- result = 'Apple pear APPLE'For a case-insensitive replacement, use REGEXP_REPLACE with the 'i' match parameter. Wrapping the source in LOWER also works, but it changes the case of the whole string, which is rarely what you want.
Left to right, without overlap
REPLACE scans from left to right. After it finds a match, it continues after that match. It never rescans text it has already replaced.
SELECT REPLACE('aaaa', 'aa', 'b') AS even_run,
REPLACE('aaa', 'aa', 'b') AS odd_run,
REPLACE('aaa', 'aa', 'a') AS not_recursive
FROM dual;
-- even_run = 'bb', odd_run = 'ba', not_recursive = 'aa'In the third case, 'aaa' becomes 'aa' and stops. If the function rescanned its own output, it would keep shrinking the string. Two consequences follow:
- Overlapping matches are not all replaced. In
'aaa', the pair at positions 2 and 3 is never considered, because position 2 was consumed by the first match. - If you need to collapse repeated characters, such as turning runs of spaces into one space, a single
REPLACEis not enough. UseREGEXP_REPLACE(s, ' +', ' ').
Whitespace and invisible characters
REPLACE(s, ' ') removes only the space character. It leaves tabs, line feeds, and carriage returns. Use CHR to name those characters:
SELECT REPLACE('line one' || CHR(10) || 'line two', CHR(10), ' ') AS one_line
FROM dual;
-- one_line = 'line one line two'CHR(9) is a tab, CHR(10) is a line feed, and CHR(13) is a carriage return. Data that came from Windows files often contains CHR(13) and CHR(10) together.
Non-string arguments
If you pass a number or a date, Oracle converts it to text implicitly, and the result is a string.
SELECT REPLACE(1234.5, '.', ',') AS euro_style
FROM dual;
-- euro_style = '1234,5'Number conversion here is simple. Date conversion depends on the session's NLS_DATE_FORMAT, so the same query can return different text for different users. Convert dates yourself with TO_CHAR(d, 'YYYY-MM-DD') before calling REPLACE.
Practical patterns
Counting occurrences
Removing a character shortens the string by one position per match. The difference in length is therefore the number of matches. For a search string longer than one character, divide by its length.
SELECT LENGTH('banana') - LENGTH(REPLACE('banana', 'a')) AS a_count,
(LENGTH('banana') - LENGTH(REPLACE('banana', 'an'))) / LENGTH('an') AS an_count
FROM dual;
-- a_count = 3, an_count = 2This trick fails for a NULL source, because LENGTH(NULL) is NULL. It is also case-sensitive.
Escaping single quotes
When you build SQL text or output for another system, you may need to double each single quote. In a literal, a quote is written as two quotes, so the call looks odd but is correct:
SELECT REPLACE('O''Brien', '''', '''''') AS escaped
FROM dual;
-- escaped = 'O''Brien' with each quote doubled: O''BrienIf you only need to pass a value into a query, use a bind variable instead. Escaping by hand is for generating text, not for avoiding SQL injection.
Previewing a cleanup before you apply it
Test a REPLACE expression with a SELECT before you put it in an UPDATE. The setup below creates a small table. The query shows the old and new values side by side, and WHERE limits the output to rows that would change.
CREATE TABLE contacts (
id NUMBER PRIMARY KEY,
phone VARCHAR2(20)
);
INSERT INTO contacts VALUES (1, '555-123-4567');
INSERT INTO contacts VALUES (2, '5559876543');
INSERT INTO contacts VALUES (3, NULL);
COMMIT;
SELECT id,
phone,
REPLACE(phone, '-') AS cleaned
FROM contacts
WHERE phone <> REPLACE(phone, '-');
-- Returns only id 1. Row 2 is unchanged, and row 3 is NULL so the comparison is not true.The WHERE condition compares the stored value with the cleaned one. Rows whose phone has no hyphen are skipped, and so is the NULL row, because a comparison with NULL is never true. A later chapter covers WHERE, UPDATE, and ORDER BY in detail.
Length limits
REPLACE can make a string longer. Replacing '&' with '&' adds four characters per match. The function itself returns up to 4000 bytes for VARCHAR2 in standard mode, or 32767 bytes if MAX_STRING_SIZE is EXTENDED. A result that goes over the limit raises an error.
- In SQL, a result over the limit raises
ORA-22835, as in this call. In aCLOB, there is no such small limit. - In an
UPDATE, a result longer than the column raisesORA-12899: value too large for column. - In PL/SQL, assigning a result to a variable that is too short raises
ORA-06502.
Check the maximum possible growth before you run a cleanup that expands text. Compare MAX(LENGTH(REPLACE(col, ...))) against the column size.
When REPLACE is the wrong tool
| Need | Better choice |
|---|---|
| Replace one character for another, character by character (for example, a mapping table) | `TRANSLATE`, which maps each character to its partner in a single pass |
| Case-insensitive replacement | `REGEXP_REPLACE` with the `'i'` parameter |
| Replace only the first or the nth match | `REGEXP_REPLACE` with position and occurrence arguments |
| Match a pattern such as "any digit" or "two or more spaces" | `REGEXP_REPLACE` |
REPLACE is the simplest and usually the fastest choice when the text to match is a fixed literal. Reach for regular expressions only when a fixed literal cannot describe what you need.
Summary of behaviors
REPLACEreplaces every non-overlapping match from left to right and does not rescan its output.- An omitted,
NULL, or empty replacement deletes the matches. - A
NULLsource returnsNULL. ANULLor empty search string returns the source unchanged. - Matching is case-sensitive.
- The function returns a new value. Only
UPDATEchanges stored data.
Exercise
What does REPLACE('aaaaa', 'aa', 'b') return, and why?
Show answer
It returns 'bba'. The function scans left to right and replaces non-overlapping matches. Positions 1-2 become 'b', positions 3-4 become 'b', and the final 'a' has no partner, so it stays.
Exercise
Write a query that counts how many commas are in the string 'a,b,c,d' without using INSTR or SUBSTR. What value does it return?
Show answer
SELECT LENGTH('a,b,c,d') - LENGTH(REPLACE('a,b,c,d', ',')) AS comma_count FROM dual; It returns 3, because removing the commas shortens the 7-character string to 4 characters.
Exercise
A column holds 'Red', 'red', and 'RED'. You run REPLACE(color, 'red', 'blue') on each value. Which rows change, and what would you use to change all three?
Show answer
Only the row holding 'red' changes, because REPLACE is case-sensitive. To change all three, use REGEXP_REPLACE(color, 'red', 'blue', 1, 0, 'i').
Exercise
What is the result of REPLACE('abc', 'b', NULL), and how does it differ from REPLACE(NULL, 'b', 'x')?
Show answer
The first returns 'ac', because a NULL replacement deletes the matches. The second returns NULL, because a NULL source always gives a NULL result.