Sub topic 3
Nesting REPLACE to clean up several characters
This chapter assumes you know SELECT, WHERE, UPDATE, and ORDER BY, understand VARCHAR2 and string literals, can use the DUAL table, and have read the earlier SUBSTR and INSTR chapters.
Nesting REPLACE calls
Each REPLACE call removes or swaps one kind of text. To clean a value with several unwanted characters, nest one call inside another. The inner call runs first.
SELECT REPLACE(REPLACE(REPLACE(REPLACE('(555) 123-4567', '(', ''), ')', ''), ' ', ''), '-', '') AS cleaned
FROM dual;
-- cleaned = '5551234567'Each call removes one character set, and a character you leave out stays in the result. Dropping the last call would leave hyphens in place.
Edge cases
Position 0, missing matches, and zero length
SELECT SUBSTR('abc', 0, 2) AS pos_zero,
SUBSTR('abc', 5) AS past_end,
INSTR('abc', 'z') AS no_match
FROM dual;
-- pos_zero = 'ab', past_end = NULL, no_match = 0A start position of 0 behaves like 1. A start past the end, or a length below 1, returns NULL. INSTR returns 0 when nothing matches, not NULL, so test for > 0.
NULL and empty strings
In Oracle, an empty string is NULL. Most functions return NULL when an argument is NULL. REPLACE is an exception when its search string is NULL: it returns the input unchanged.
SELECT REPLACE(NULL, '-', '') AS a,
REPLACE('abc', NULL, 'x') AS b,
SUBSTR(NULL, 1, 2) AS c,
'abc' || NULL AS d
FROM dual;
-- a = NULL, b = 'abc', c = NULL, d = 'abc'Using the functions in WHERE, UPDATE, and ORDER BY
SELECT email FROM customers
WHERE SUBSTR(email, INSTR(email, '@') + 1) = 'example.com';
UPDATE customers
SET phone = REPLACE(REPLACE(phone, '-', ''), ' ', '');
SELECT full_name FROM customers
ORDER BY SUBSTR(full_name, INSTR(full_name, ' ') + 1);When to use REGEXP_* or TRANSLATE
| Function | Use it when |
|---|---|
| REGEXP_SUBSTR, REGEXP_INSTR | You need to match a pattern, not a fixed string |
| REGEXP_REPLACE | You remove or replace many kinds of characters, such as every non-digit: `REGEXP_REPLACE(phone, '[^0-9]', '')` |
| TRANSLATE | You map single characters one for one, or drop characters that have no match in the second argument |
TRANSLATE returns NULL if its third argument is an empty string, so use a non-empty value when you want to delete characters.
Byte and character semantics
SUBSTRB and INSTRB count bytes. SUBSTRC counts characters. In a multibyte character set such as AL32UTF8, é takes two bytes.
SELECT SUBSTRB('café', 4, 2) AS by_bytes,
SUBSTRC('café', 4, 1) AS by_chars,
INSTRB('café', 'é') AS byte_pos
FROM dual;
-- by_bytes = 'é', by_chars = 'é', byte_pos = 4Exercise
Exercise
What does REPLACE('a-b-c', '-') return, and what does SUBSTR('abc', 1, 0) return?
Show answer
REPLACE returns 'abc' because omitting the replacement string removes every match. SUBSTR returns NULL because a length below 1 returns NULL.