Sub topic 8
Nesting REPLACE to clean up several characters
This chapter assumes you know how a single REPLACE(string, search, replacement) call works, including that omitting the replacement removes the match. It also assumes you are comfortable with SELECT ... FROM dual and with the fact that Oracle treats an empty string as NULL. Here you will learn how to chain several REPLACE calls, how the order of the chain changes the result, and when a chain becomes the wrong tool.
Why one REPLACE is not enough
A single REPLACE handles one search string. Real data usually has several unwanted characters at once. Phone numbers arrive as (555) 123-4567, 555.987.6543, or 555 222 3333. To compare them or store them in one format, you need to remove parentheses, spaces, hyphens, and dots.
You cannot pass a list of characters to REPLACE. Instead, you feed the output of one call into the next. This is called nesting.
How nesting evaluates
Oracle evaluates the innermost call first. Its result becomes the first argument of the call that wraps it, and so on outward.
SELECT REPLACE(REPLACE('(555) 123-4567', '(', ''), ')', '') AS step_two
FROM dual;
-- step_two = '555 123-4567'The inner call turns (555) 123-4567 into 555) 123-4567. The outer call then removes ) and gives 555 123-4567. Each layer works on the text left by the layer inside it, not on the original string.
Two rules from the single-call behavior still apply at every layer:
REPLACEis case-sensitive.REPLACE('Ab', 'a', 'x')changes nothing.- A NULL or omitted replacement removes the match. A NULL search string leaves the input unchanged. A NULL input returns NULL.
Building a full cleanup chain
The earlier example in this tutorial removed (, ), and the space, but the hyphen stayed because it was never listed. Each character you want gone needs its own layer. Here is the complete version.
SELECT REPLACE(
REPLACE(
REPLACE(
REPLACE('(555) 123-4567', '(', ''),
')', ''),
' ', ''),
'-', '') AS cleaned
FROM dual;
-- cleaned = '5551234567'Formatting the chain with one line per layer and the search argument beside its closing parenthesis makes it easier to check that every layer has a matching pair. Because the replacement is optional, you can also write each layer as REPLACE(x, '('), which is shorter. Writing '' explicitly makes the intent to delete obvious to later readers.
The diagram shows the string as it passes through the four layers, from the innermost call outward.
Applying the chain to table data
A chain works on a column exactly as it does on a literal. This query cleans several formats at once and filters on the cleaned value.
WITH contacts (id, phone) AS (
SELECT 1, '(555) 123-4567' FROM dual UNION ALL
SELECT 2, '555.987.6543' FROM dual UNION ALL
SELECT 3, '555 222 3333' FROM dual
)
SELECT id,
phone,
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone, '(', ''), ')', ''), ' ', ''), '-', ''), '.', '') AS digits
FROM contacts
WHERE REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone, '(', ''), ')', ''), ' ', ''), '-', ''), '.', '') LIKE '555%';
-- id 1 -> 5551234567
-- id 2 -> 5559876543
-- id 3 -> 5552223333The chain appears twice, which is a sign that the expression deserves a name. An inline view (a subquery in FROM) or a virtual column lets you write the chain once.
SELECT id, digits
FROM (
SELECT id,
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(phone, '(', ''), ')', ''), ' ', ''), '-', ''), '.', '') AS digits
FROM (SELECT 1 AS id, '(555) 123-4567' AS phone FROM dual)
)
WHERE digits LIKE '555%';
-- id = 1, digits = 5551234567To fix stored data, put the same chain in an UPDATE. The WHERE clause skips rows that have nothing to clean, which reduces the number of rows written and the undo and redo generated.
CREATE TABLE contacts_demo (id NUMBER, phone VARCHAR2(30));
INSERT INTO contacts_demo VALUES (1, '(555) 123-4567');
INSERT INTO contacts_demo VALUES (2, '5559876543');
UPDATE contacts_demo
SET phone = REPLACE(REPLACE(REPLACE(REPLACE(phone, '(', ''), ')', ''), ' ', ''), '-', '')
WHERE phone <> REPLACE(REPLACE(REPLACE(REPLACE(phone, '(', ''), ')', ''), ' ', ''), '-', '');
-- 1 row updated (row 2 is skipped)Rows where phone is NULL are also skipped, because NULL <> NULL is not true. That is usually what you want here.
Order matters
For independent single characters such as ( and ), the order of layers does not change the result. In several other cases it does.
Replacements that feed each other
Trying to swap two words with two layers fails, because the second layer sees the output of the first.
SELECT REPLACE(REPLACE('cat dog', 'cat', 'dog'), 'dog', 'cat') AS attempted_swap
FROM dual;
-- attempted_swap = 'cat cat'The inner call produces dog dog, and the outer call turns both into cat. A correct swap uses a placeholder that cannot occur in the data.
SELECT REPLACE(REPLACE(REPLACE('cat dog', 'cat', '#1#'), 'dog', 'cat'), '#1#', 'dog') AS swapped
FROM dual;
-- swapped = 'dog cat'Escaping special characters
Escaping a string for markup is a common ordering trap. The ampersand must be replaced first, because every later layer introduces new ampersands.
SELECT REPLACE(REPLACE('a < b & c', '&', '&'), '<', '<') AS escaped
FROM dual;
-- escaped = 'a < b & c'If you reverse the layers, < becomes < first and the ampersand layer then turns it into &lt;.
Longer and shorter overlapping strings
When one search string contains another, handle the longer one first. To remove both Mr. and Mr from a name, the longer pattern goes in the inner call.
SELECT REPLACE(REPLACE('Mr. Smith, Mr Jones', 'Mr.', ''), 'Mr', '') AS names
FROM dual;
-- names = ' Smith, Jones'With the order reversed, the inner call would leave a stray . behind.
REPLACE does not rescan its own output
Within a single call, Oracle scans left to right and does not look again at text it just produced or removed. Removing a match can create a new match that the same call does not catch.
SELECT REPLACE('aabb', 'ab', '') AS one_pass,
REPLACE(REPLACE('aabb', 'ab', ''), 'ab', '') AS two_passes
FROM dual;
-- one_pass = 'ab', two_passes = NULLAfter the first removal the string is ab, which contains the pattern again. The second layer removes it, leaving an empty string, and Oracle returns that as NULL. Keep this in mind whenever the result of a cleanup is displayed or concatenated: NULL || 'x' is 'x', but NULL = '' is never true.
Collapsing runs of spaces
Repeated spaces are a classic case of the no-rescan rule. A first attempt replaces two spaces with one.
SELECT REPLACE('a b', ' ', ' ') AS one_pass
FROM dual;
-- one_pass = 'a b'Four spaces contain two non-overlapping pairs, so each pair becomes one space and two remain. You would need to repeat the layer an unknown number of times. A placeholder pattern collapses any run in three layers.
SELECT REPLACE(REPLACE(REPLACE('a b c', ' ', '<>'), '><', ''), '<>', ' ') AS collapsed
FROM dual;
-- collapsed = 'a b c'The steps work like this:
- Each space becomes
<>, so a run of n spaces becomes n copies of<>. - Every adjacent
><pair (the end of one copy and the start of the next) is removed. That leaves a single<>for the whole run. - The remaining
<>markers become single spaces.
This only works if <> never occurs in the original text. Pick a placeholder that cannot appear in your data. Oracle also has REGEXP_REPLACE(s, ' {2,}', ' ') for this job, which is clearer if you can use it.
Control characters
Imported text often contains line breaks and tabs. You cannot type these inside a string literal, so build them with CHR.
SELECT REPLACE(REPLACE(REPLACE('line1' || CHR(13) || CHR(10) || 'line2' || CHR(9) || 'end',
CHR(13)), CHR(10), ' '), CHR(9), ' ') AS flattened
FROM dual;
-- flattened = 'line1 line2 end'Here CHR(13) (carriage return) is removed, CHR(10) (line feed) becomes a space, and CHR(9) (tab) becomes a space. Handling CHR(13) and CHR(10) separately covers both Windows (CR LF) and Unix (LF) line endings.
When a chain is the wrong tool
Every layer is another full pass over the string, and long chains are hard to read and easy to get wrong. Consider these alternatives once a chain passes about four or five layers.
| Goal | Chain of REPLACE | Alternative |
|---|---|---|
| Remove a fixed set of single characters | One layer per character | `TRANSLATE(s, 'x()- .', 'x')` |
| Keep only digits | Cannot be listed fully | `REGEXP_REPLACE(s, '[^0-9]')` |
| Collapse repeated spaces | Placeholder trick | `REGEXP_REPLACE(s, ' {2,}', ' ')` |
| Swap or map several words | Placeholders, order-sensitive | Several `REPLACE` layers, or a lookup table and a join |
TRANSLATE maps characters one to one by position. The common deletion idiom puts a dummy character first in both lists, because Oracle returns NULL if the third argument is empty.
SELECT TRANSLATE('(555) 123-4567', 'x()- .', 'x') AS cleaned
FROM dual;
-- cleaned = '5551234567'The dummy x maps to itself. Every other listed character has no partner, so it is deleted. Note that x would also be left alone in the data, so choose a dummy that is not one of the characters you want to remove. TRANSLATE works on single characters only. When you need to replace whole substrings, such as Mr. or &, nesting REPLACE remains the right approach.
Common errors
- Missing the hyphen or dot. Each character needs its own layer, so check the data for formats you did not expect.
- Unbalanced parentheses. Deeply nested calls are easy to break. Format one layer per line.
- Wrong order. Replace
&before the characters that introduce&, and longer strings before the shorter strings they contain. - Case.
REPLACEis case-sensitive. Wrap the input inUPPERorLOWERif you need a case-insensitive match, and note this changes the output case too. - Treating an empty result as an empty string. A fully removed string is NULL in Oracle, so
WHERE col = ''never matches. UseIS NULL.
Exercise
Write a query that turns the string 'Tel: 555-123.4567 ext 9' into 'Tel:5551234567ext9' using nested REPLACE calls. Then explain why REPLACE(REPLACE('a&b', '&', '&'), 'amp', 'x') does not give 'a&b'.
Show answer
SELECT REPLACE(REPLACE(REPLACE('Tel: 555-123.4567 ext 9', ' ', ''), '-', ''), '.', '') FROM dual; returns 'Tel:5551234567ext9'. The second query does not give 'a&b' because the inner call produces 'a&b', and the outer call then replaces 'amp' inside that new text, giving 'a&x;b'. The outer layer sees the output of the inner layer, not the original string.
Exercise
The string is 'x y z' (two spaces, then three spaces). Using the placeholder technique with '<>', write the query that returns 'x y z', and state what each of the three layers produces.
Show answer
SELECT REPLACE(REPLACE(REPLACE('x y z', ' ', '<>'), '><', ''), '<>', ' ') FROM dual; The inner layer gives 'x<><>y<><><>z'. The middle layer removes each '><' pair, giving 'x<>y<>z'. The outer layer turns each '<>' into one space, giving 'x y z'.