replace(text, text, text) — Replace every occurrence of a substring
Last updated: 2026-11-04
replace(text, text, text) — Replace every occurrence of a substring
replace() swaps every occurrence of the from substring for the to substring and returns the new string. It is the usual tool for scrubbing dirty data, masking sensitive values or normalising separators; note that it replaces all matches rather than just the first, so one-off substitutions need a different approach.
| Kind | function |
|---|---|
| Example Language | SQL |
📝 Syntax
replace(string text, from text, to text) → text
⚙️ Parameters
| string text | The original string. Type text. |
|---|---|
| from text | The substring to replace (case sensitive). Type text. |
| to text | The replacement substring; pass an empty string to delete. Type text. |
Returns:text — the string after replacement. Returns NULL if any argument is NULL.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
id | slug | slug_underscore | replaced
----+------------------------+------------------------+---------------------
1 | hello-world-postgresql | hello_world_postgresql | hi-world-postgresql
2 | hello-world-mysql | hello_world_mysql | hi-world-mysql
3 | no-match-here | no_match_here | no-match-here
(3 rows)
📌 Key Points
- replace() replaces every match, not just the first one.
- Matching is case sensitive; use regexp_replace() for case-insensitive substitution.
- The result is NULL if any argument is NULL, and passing an empty string as to deletes the matched text.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QHow do I replace only the first occurrence of "hello world" with "hi world"?
Areplace() replaces all of them. Use regexp_replace(s, 'hello', 'hi') without the 'g' flag to replace only the first match, or overlay() to splice a replacement at an exact position.