PostgreSQL REPLACE() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL REPLACE()
function to replace a substring with a new one.
Introduction to PostgreSQL REPLACE() function
The REPLACE()
function replaces all occurrences of a substring with a new one in a string.
Here’s the syntax of the PostgreSQL REPLACE()
function:
The REPLACE()
function accepts three arguments:
source
: This is an input string that you want to replace.from_text
: This is the substring that you want to search and replace. If thefrom_text
appears multiple times in thesource
string, the function will replace all the occurrences.to_text
: This is the new substring that you want to replace thefrom_text
.
PostgreSQL REPLACE() function examples
Let’s explore some examples of using the REPLACE()
function.
1) Basic PostgreSQL REPLACE() function example
The following example uses the REPLACE()
function to replace the string 'A'
in the string 'ABC AA'
with the string 'Z'
:
Output:
In this example, the REPLACE()
function replaces all the characters 'A'
with the character 'Z'
in a string.
2) Using the PostgreSQL REPLACE() function with table data
If you want to search and replace a substring in a table column, you use the following syntax:
Let’s see the following example.
First, create a new table called posts
that has three columns id
, title
, and url
:
Output:
Second, replace the http
in the url
column with the https
using the REPLACE()
function:
Output:
The output indicates that three rows were updated.
Third, verify the update by retrieving data from the customer
table:
Output:
The output indicates that the http
in the url
column were replaced by the https
.
Summary
- Use the PostgreSQL
REPLACE()
function to replace all occurrences of a substring in a string with another a new substring.