PostgreSQL – REPLACE() Function
Last Updated :
08 Jul, 2024
In PostgreSQL, the REPLACE function is an essential string manipulation tool that allows users to search for and replace all occurrences of a specific substring within a given string. This function is particularly useful for data cleaning, formatting, and updating textual data.
Let us get a better understanding of the REPLACE Function in PostgreSQL from this article.
Syntax
The basic syntax of the REPLACE function in PostgreSQL is as follows:
REPLACE(source, old_text, new_text );
Parameters:
- source: The original string where you want to replace a substring.
- old_text: The substring that you want to search for within the source string. All occurrences of this substring will be replaced.
- new_text: The new substring that will replace each occurrence of the old_text.
PostgreSQL REPLACE Function Examples
Example 1: Replacing Substrings in a URL
The following statement replaces the substring ‘tt’ with ‘xx’ in a URL:
SELECT REPLACE ( 'https://www.geeksforgeeks.org', 'tt', 'xx' );
Output:

Explanation: The REPLACE function searched for the substring ‘tt’ within the provided URL, but since there were no occurrences of ‘tt’ in the URL, the output remains unchanged.
Example 2: Updating Email Domains in a Database Table
The below statement updates the email column to replace the domain ‘sakilacustomer.org’ with ‘geeksforgeek.org’, in the customer table of the sample database, ie, dvdrental:
UPDATE customer
SET email = REPLACE ( email, 'sakilacustomer.org', 'geeksforgeeks.org' );
To verify it use the below statement:
SELECT first_name, last_name, email
FROM customer;
Output:

Explanation: This output displays the updated email addresses along with the first and last names of the customers, confirming that the email domains have been successfully updated.
Important Points About PostgreSQL REPLACE Function
- The PostgreSQL
REPLACE function replaces all occurrences of a specified substring within a given string.
- The
REPLACE function is case-sensitive. This means it distinguishes between uppercase and lowercase characters.
- Frequent use of the
REPLACE function in large datasets can impact performance. Ensure your tables are indexed appropriately to mitigate this.
- The
REPLACE function itself does not modify the source data unless used within an UPDATE statement.