Sub topic 9
Replacing text with replace, translate and overlay
This chapter covers three functions that change part of a string: replace, translate and overlay. It assumes you can write basic SELECT, WHERE and UPDATE statements, and that you know NULL propagates through most string functions. Earlier chapters showed how to find text with strpos. Here you will change it.
Choosing the right function
The three functions differ in what they match. replace matches a substring. translate matches single characters. overlay matches a position.
| Function | Matches on | Replaces | Typical use |
|---|---|---|---|
| `replace(s, from, to)` | A substring, case-sensitive | Every occurrence | Swap a word, a separator or a prefix |
| `translate(s, from, to)` | Individual characters | Each character, one for one | Strip punctuation, map characters |
| `overlay(s PLACING new FROM n [FOR k])` | A position and a length | One span | Mask digits, patch a fixed-width field |
replace: swap every occurrence of a substring
The signature is replace(string, from, to). It replaces every non-overlapping occurrence of from with to.
SELECT replace('a-b-c', '-', '/') AS slashes,
replace('banana', 'an', 'AN') AS every_match,
replace('Hello hello', 'hello', 'X') AS case_sensitive,
replace('abc', 'b', '') AS deleted;The results are a/b/c, bANANa, Hello X and ac. Three properties matter in practice:
- It is literal. The
fromargument is not a pattern.replace('a.b', '.', '-')returnsa-b, and the dot is not a wildcard. - It is case-sensitive. The second row above leaves
Hellounchanged. For case-insensitive replacement, useregexp_replacewith theiflag, covered in a later chapter. - An empty
todeletes the match. An emptyfrommatches nothing, so the string comes back unchanged.
Chaining and the order of replacements
Each replace sees the output of the previous one. Order therefore changes the result. Escaping HTML is the classic case:
SELECT replace(replace(replace('Fish & <Chips>', '&', '&'),
'<', '<'),
'>', '>') AS escaped;This returns Fish & <Chips>. The & must be handled first. If you replaced < first, the & inside < would be escaped again and you would get &lt;.
Chaining also causes surprises when a replacement contains the text you are searching for. Because replace makes a single pass per call, replace('aaa', 'a', 'aa') returns aaaaaa. It does not loop forever.
Using replace in an UPDATE
replace is often used to fix data in bulk. Because it matches anywhere in the string, restrict the rows so you change only what you intend.
CREATE TEMP TABLE products (id int, sku text);
INSERT INTO products VALUES (1, 'OLD-100'), (2, 'OLD-200'), (3, 'X-OLD-5'), (4, NULL);
UPDATE products
SET sku = replace(sku, 'OLD-', 'NEW-')
WHERE sku LIKE 'OLD-%';
SELECT * FROM products ORDER BY id;Row 3 keeps X-OLD-5 because the WHERE clause matches only skus that start with OLD-. Without that filter, replace would also have changed row 3 to X-NEW-5. Row 4 holds NULL. replace(NULL, ...) is NULL, and NULL LIKE ... is not true, so the row is untouched either way.
translate: map characters one for one
The signature is translate(string, from, to). It reads string one character at a time. If a character appears in from, it is replaced by the character at the same position in to.
SELECT translate('hello world', 'lo', '01') AS mapped,
translate('12345', '143', 'ax') AS short_to,
translate('café', 'é', 'e') AS accent_removed;The results are he001 w1r0d, a2x5 and cafe.
The second example shows the rule for unequal lengths. In translate('12345', '143', 'ax'), 1 maps to a and 4 maps to x. 3 has no partner in to, so it is deleted. This gives a compact way to remove characters: leave to empty, or make it shorter than from.
SELECT translate('(555) 123-4567', '()- ', '') AS digits_only;This returns 5551234567. All four characters in from are deleted, including the space.
The edge cases to remember are these:
- If a character appears more than once in
from, the first occurrence decides its mapping.translate('abc', 'aa', 'xy')returnsxbc. - If
tois longer thanfrom, the extra characters intoare ignored. translateworks on characters, not bytes, so multibyte characters such aséare handled correctly in a UTF8 database.translatecannot replace one character with several. Mappingétoeeis impossible. Usereplacefor that.
overlay: replace by position
The signature is overlay(string PLACING newstring FROM start [FOR count]). It removes count characters beginning at the 1-based position start, then inserts newstring in their place. Both the removed span and the inserted text can be any length.
SELECT overlay('Txxxxas' PLACING 'hom' FROM 2 FOR 4) AS name,
overlay('abcdef' PLACING 'XY' FROM 3) AS default_count,
overlay('abcdef' PLACING 'XY' FROM 3 FOR 0) AS inserted;The results are Thomas, abXYef and abXYcdef.
- When
FORis omitted,countdefaults to the length ofnewstring. The second example removes two characters,cd, and inserts two. FOR 0removes nothing, sooverlayacts as an insert.- A
countdifferent from the length ofnewstringmakes the result longer or shorter. The first example replaces four characters with three.
overlay suits fixed-width data, where you know where a field sits. A common use is masking:
SELECT overlay('4111111111111111' PLACING repeat('*', 12) FROM 1 FOR 12) AS masked,
overlay('555-123-4567' PLACING 'XXX' FROM 5 FOR 3) AS hidden_exchange;This returns ************1111 and 555-XXX-4567. Using repeat('*', n) keeps the mask length tied to FOR n, so the two numbers cannot drift apart.
If you only know the text and not the position, combine overlay with strpos:
SELECT overlay('report_2025.csv' PLACING '2026'
FROM strpos('report_2025.csv', '2025') FOR 4) AS renamed;This returns report_2026.csv. For this case replace is simpler. It also replaces every occurrence, while this overlay call changes only the first.
NULL behavior
All three functions are strict. If any argument is NULL, the result is NULL. This matters most for to values that come from a column or a subquery:
SELECT replace('abc', 'b', NULL) AS r,
translate('abc', 'b', NULL) AS t,
overlay('abc' PLACING NULL FROM 1) AS o,
replace('abc', 'b', '') AS empty_not_null;The first three columns are NULL. The last is ac. An empty string is a value, and NULL is not. If you want a NULL replacement to mean "delete", wrap it: replace(s, 'b', coalesce(x, '')).
Common mistakes
- Expecting case-insensitive matching.
replace('Cat', 'cat', 'dog')returnsCat. Useregexp_replace('Cat', 'cat', 'dog', 'i'). - Using translate for multi-character targets.
translate('abc', 'ab', 'x')deletesband does not replaceab. It works on characters, not substrings. - Forgetting that UPDATE rewrites unchanged rows.
UPDATE t SET c = replace(c, 'x', 'y')with noWHEREwrites a new row version for every row, even where nothing changed. AddWHERE c LIKE '%x%'to avoid that. - Off-by-one positions in overlay. Positions start at 1.
FROM 0or a negative start does not count from the end. The characters beforestartare kept withsubstring(s FROM 1 FOR start - 1), which returns an empty string for those values. - Order-dependent chains. Check the order whenever one replacement's output contains another's input, as in the HTML example.
Exercise
A column phone holds values like (555) 123-4567. Write an expression that returns the digits only, then an expression that replaces the first three digits of the digits-only result with ***. What do both return for that sample value?
Show answer
Digits only: translate(phone, '()- ', ''), which returns 5551234567. Masked: overlay(translate(phone, '()- ', '') PLACING '***' FROM 1 FOR 3), which returns ***1234567. The translate call deletes every character in from because to is empty. The overlay call removes three characters starting at position 1 and inserts the three asterisks.
Exercise
What does replace(replace('a<b', '<', '<'), '&', '&') return, and why is it wrong for HTML escaping? How do you fix it?
Show answer
It returns a&lt;b. The first call produces a<b, and the second call then escapes the & that the first call just added. To fix it, escape & first: replace(replace('a<b', '&', '&'), '<', '<') returns a<b.