PostgreSQL – REPLACE Function

The REPLACE function is used to replace all occurrences of a specified substring within a given string with another substring. The syntax of the REPLACE function is as follows:

REPLACE(string, old_substring, new_substring)

where string is the input string in which you want to perform replacements,

and old_substring is the substring you want to replace within the input string,

and new_substring is the substring that will replace the occurrences of the old_substring.

Here’s an example of how you might use the REPLACE function in a SQL query:

SELECT REPLACE('Hello, World!', 'o', 'i') AS modified_string;

In this example, the result would be the string 'Helli, Wirld!', as all occurrences of the letter 'o' were replaced with 'i'.

The REPLACE function is case-sensitive. If you want to perform a case-insensitive replacement, you can convert both the input string and the substrings to a common case using functions like LOWER or UPPER before using the REPLACE function.

SELECT REPLACE(UPPER('Hello, World!'), UPPER('o'), 'I') AS modified_string;

This would result in the string 'HELLI, WIRLD!'.

Keep in mind that the REPLACE function replaces all occurrences of the specified substring within the input string. If you only want to replace a specific occurrence or a certain number of occurrences, you might need to use more advanced string manipulation techniques or regular expressions.

Similar Posts