The REPLACE function is used to replace all occurrences of a specified substring in a string with a new substring. This function replaces all matching instances of the substring in the string, performing a global replace operation.
Difference from REPLACE_EMPTY function:
REPLACE() replaces the specified substring, including empty stringsREPLACE_EMPTY() is specifically used to replace empty values or empty strings with a specified valueREPLACE(<str>, <old>, <new>)
| Parameter | Description |
|---|---|
<str> | The source string where replacement will occur. Type: VARCHAR |
<old> | The target substring to be replaced. If not found in str, no replacement occurs. Type: VARCHAR |
<new> | The new substring used to replace old. Type: VARCHAR |
Returns VARCHAR type, representing the new string after replacement.
Replacement rules:
Special cases:
SELECT REPLACE('hello world', 'world', 'universe');
+---------------------------------------------+ | REPLACE('hello world', 'world', 'universe') | +---------------------------------------------+ | hello universe | +---------------------------------------------+
SELECT REPLACE('apple apple apple', 'apple', 'orange');
+------------------------------------------------+ | REPLACE('apple apple apple', 'apple', 'orange') | +------------------------------------------------+ | orange orange orange | +------------------------------------------------+
SELECT REPLACE('banana', 'a', '');
+---------------------------+ | REPLACE('banana', 'a', '') | +---------------------------+ | bnn | +---------------------------+
SELECT REPLACE(NULL, 'old', 'new'), REPLACE('test', NULL, 'new'), REPLACE('test', 'old', NULL);
+------------------------------+------------------------------+------------------------------+ | REPLACE(NULL, 'old', 'new') | REPLACE('test', NULL, 'new') | REPLACE('test', 'old', NULL) | +------------------------------+------------------------------+------------------------------+ | NULL | NULL | NULL | +------------------------------+------------------------------+------------------------------+
SELECT REPLACE('ṭṛì ḍḍumai test ṭṛì ḍḍumannàri', 'ṭṛì', 'replaced');
+-----------------------------------------------------------+ | REPLACE('ṭṛì ḍḍumai test ṭṛì ḍḍumannàri', 'ṭṛì', 'replaced') | +-----------------------------------------------------------+ | replaced ḍḍumai test replaced ḍḍumannàri | +-----------------------------------------------------------+