EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PostgreSQL Tutorial PostgreSQL replace
Secondary Sidebar
PostgreSQL Tutorial
  • Basic
    • What is PostgreSQL
    • PostgreSQL Features
    • How to Install PostgreSQL
    • PostgreSQL Versions
    • PostgreSQL Architecture
    • PostgreSQL GUI
    • Postgres Command-Line
    • PostgreSQL Variables
    • PostgreSQL Data Types
    • PostgreSQL NOT NULL
    • PostgreSQL Integer
    • PostgreSQL Boolean
    • PostgreSQL BIGINT
    • PostgreSQL NULLIF
    • PostgreSQL Administration
    • PostgreSQL Commands
    • PostgreSQL Operators
    • PostgreSQL IN Operator
    • Postgres like query
    • PostgreSQL encode
    • PostgreSQL Cheat Sheet
    • PostgreSQL List Databases
    • PostgreSQL Rename Database
  • Control Statement
    • PostgreSQL IF Statement
    • PostgreSQL if else
    • PostgreSQL CASE Statement
    • PostgreSQL LOOP
    • PostgreSQL For Loop
    • PostgreSQL While Loop
  • Joins
    • Joins in PostgreSQL
    • PostgreSQL Inner Join
    • PostgreSQL Outer Join
    • LEFT OUTER JOIN in PostgreSQL
    • PostgreSQL FULL OUTER JOIN
    • PostgreSQL LEFT JOIN
    • PostgreSQL Full Join
    • PostgreSQL Cross Join
    • PostgreSQL NATURAL JOIN
    • PostgreSQL UPDATE JOIN
  • Queries
    • PostgreSQL Queries
    • PostgreSQL INSERT INTO
    • PostgreSQL WHERE Clause
    • PostgreSQL WITH Clause
    • PostgreSQL ORDER BY
    • PostgreSQL ORDER BY Random
    • PostgreSQL ORDER BY DESC
    • PostgreSQL GROUP BY
    • PostgreSQL group_concat
    • PostgreSQL HAVING
    • PostgreSQL Recursive Query
  • Advanced
    • PostgreSQL Schema
    • Postgres List Schemas
    • PostgreSQL Drop Schema
    • PostgreSQL VARCHAR
    • Array in PostgreSQL
    • PostgreSQL DDL
    • PostgreSQL List Users
    • Postgres Default User
    • Postgres add user
    • PostgreSQL User Password
    • PostgreSQL log_statement
    • PostgreSQL repository
    • PostgreSQL shared_buffer
    • PostgreSQL String Functions
    • PostgreSQL Compare Strings
    • PostgreSQL Text Search
    • PostgreSQL TEXT
    • PostgreSQL String Array
    • PostgreSQL where in array
    • PostgreSQL Constraints
    • PostgreSQL UNIQUE Constraint
    • PostgreSQL CHECK Constraint
    • PostgreSQL INTERSECT
    • PostgreSQL Like
    • Cursors in PostgreSQL
    • PostgreSQL UNION ALL
    • Indexes in PostgreSQL
    • PostgreSQL Index Types
    • PostgreSQL REINDEX
    • PostgreSQL UNIQUE Index
    • PostgreSQL Clustered Index
    • PostgreSQL DROP INDEX
    • PostgreSQL DISTINCT
    • PostgreSQL FETCH
    • PostgreSQL RAISE EXCEPTION
    • PostgreSQL Auto Increment
    • Sequence in PostgreSQL
    • Wildcards in PostgreSQL
    • PostgreSQL Subquery
    • PostgreSQL Alias
    • PostgreSQL LIMIT
    • PostgreSQL Limit Offset
    • PostgreSQL LAG()
    • PostgreSQL Table
    • Postgres Show Tables
    • PostgreSQL Describe Table
    • PostgreSQL Lock Table
    • PostgreSQL ALTER TABLE
    • Postgres Rename Table
    • PostgreSQL List Tables
    • PostgreSQL TRUNCATE TABLE
    • PostgreSQL Table Partitioning
    • Postgres DROP Table
    • PostgreSQL Functions
    • PostgreSQL Math Functions
    • PostgreSQL Window Functions
    • Aggregate Functions in PostgreSQL
    • PostgreSQL Primary Key
    • Foreign Key in PostgreSQL
    • PostgreSQL Procedures
    • PostgreSQL Stored Procedures
    • PostgreSQL Views
    • PostgreSQL Materialized Views
    • Postgres Create View
    • PostgreSQL Triggers
    • PostgreSQL DROP TRIGGER
    • PostgreSQL Date Functions
    • PostgreSQL TO_DATE()
    • PostgreSQL datediff
    • PostgreSQL Timestamp
    • PostgreSQL CURRENT_TIMESTAMP()
    • PostgreSQL Notify
    • PostgreSQL LENGTH()
    • PostgreSQL blob
    • PostgreSQL Median
    • PostgreSQL kill query
    • PostgreSQL Formatter
    • PostgreSQL RANK()
    • PostgreSQL Select
    • PostgreSQL Average
    • PostgreSQL DATE_PART()
    • PostgreSQL EXECUTE
    • PostgreSQL COALESCE
    • PostgreSQL EXTRACT()
    • PostgreSQL Sort
    • PostgreSQL TO_CHAR
    • PostgreSQL Interval
    • PostgreSQL Number Types
    • PostgreSQL ROW_NUMBER
    • Alter Column in PostgreSQL
    • PostgreSQL Identity Column
    • PostgreSQL SPLIT_PART()
    • PostgreSQL CONCAT()
    • PostgreSQL replace
    • PostgreSQL TRIM()
    • PostgreSQL MAX
    • PostgreSQL DELETE
    • PostgreSQL Float
    • PostgreSQL OID
    • PostgreSQL log
    • PostgreSQL REGEXP_MATCHES()
    • PostgreSQL MD5 
    • PostgreSQL NOW()
    • PostgreSQL RANDOM
    • PostgreSQL round
    • PostgreSQL Trunc()
    • PostgreSQL TIME
    • PostgreSQL IS NULL
    • PostgreSQL CURRENT_TIME
    • PostgreSQL MOD()
    • Postgresql Count
    • PostgreSQL Datetime
    • PostgreSQL MIN()
    • PostgreSQL age()
    • PostgreSQL enum
    • PostgreSQL OR
    • PostgreSQL Wal
    • PostgreSQL NOT IN
    • PostgreSQL SET
    • PostgreSQL Current Date
    • PostgreSQL Compare Date
    • PostgreSQL SERIAL
    • PostgreSQL UUID
    • PostgreSQL Merge
    • PostgreSQL Database
    • PostgreSQL Clone Database
    • PostgreSQL Copy Database
    • PostgreSQL Show Databases
    • PostgreSQL Restore Database
    • PostgreSQL DROP DATABASE
    • PostgreSQL ALTER DATABASE
    • Postgres DROP Database
    • Postgres Dump Database
    • PostgreSQL OFFSET
    • PostgreSQL GRANT
    • PostgreSQL COMMIT
    • PostgreSQL ROLLUP
    • PostgreSQL JSON
    • EXPLAIN ANALYZE in PostgreSQL
    • PostgreSQL Temporary Table
    • PostgreSQL Show Tables
    • PostgreSQL cluster
    • PostgreSQL Replication
    • PostgreSQL Logical Replication
    • PostgreSQL flush privileges
    • PostgreSQL Tablespaces
    • CAST in PostgreSQL
    • PostgreSQL CTE
    • hstore in PostgreSQL
    • PostgreSQL Encryption
    • PostgreSQL DECODE()
    • PostgreSQL Vacuum
    • PostgreSQL EXCLUDE
    • Postgres Change Password
    • Postgres Delete Cascade
    • PostgreSQL EXCEPT
    • PostgreSQL Roles
    • PostgreSQL Link
    • PostgreSQL Partition
    • PostgreSQL column does not exist
    • PostgreSQL Log Queries
    • PostgreSQL escape single quote
    • PostgreSQL Query Optimization
    • PostgreSQL Character Varying
    • PostgreSQL Transaction
    • PostgreSQL Extensions
    • PostgreSQL Import CSV
    • PostgreSQL Client
    • PostgreSQL caching
    • PostgreSQL Incremental Backup
    • PostgreSQL JSON vs JSONNB
    • PostgreSQL JDBC Driver
    • PostgreSQL Interview Questions

PostgreSQL replace

By Payal UdhaniPayal Udhani

PostgreSQL replace

Introduction to PostgreSQL replace

The following article provides an outline on PostgreSQL replace. When we manipulate strings or work with strings in PostgreSQL, we require many functions to perform operations. PostgreSQL provides us with many string manipulating functions. One of them is the REPLACE() method that can be used to replace the substring from the original string to some other substring that you wish to. Besides this, we can even replace the strings that match the particular regular expression that we know by using the REGEXP_REPLACE() method. There is the TRANSLATE() method available that helps us replace the set of substrings with a particular substring in the original string.

Syntax:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

REPLACE(original_string, old_sub_string, new_sub_string );

  • original_string: This is the source string, the original string that contains some substring that you wish to replace.
  • old_sub_string: This is the substring that is present in the original string and which you want to replace. It can be present at any number of times in the source string.
  • new_sub_string: This is the substring with which the old substring value should be replaced.

The replace() function replaces all the occurrences of old_sub_string to new_sub_string in the original_string.

Examples of PostgreSQL replace

Given below are the examples mentioned:

Example #1

Let us consider one string, “The waves of the sea help us to get back to ourselves.” in which we want sea words to replace with the ocean. We can do so by using the replace() function in the following way.

Code:

select replace('The waves of the sea help us to get back to ourselves.', 'sea', 'ocean');

Output:

PostgreSQL replace 1

Example #2

‘We can do this. We shall do this.’ This is the sentence in which we want to replace the “this” word with “that” word. For this, we will use the following query statement.

Code:

select replace('We can do this. We shall do this.','this','that');

Output:

 We can do this. We shall do this

Note that both the occurrences of “this” are replaced with “that” word.

Example #3

Instead of replacing the word, let us replace the substring in the original string. Consider a string “The sky is beautiful and calm at night. The sky is warm and sunny in the morning.” and replace the substring “The sky is” with “Breeze and air are” substring. For doing this, we will again use the replace() method, and our query statement will be as follows.

Code:

select replace('The sky is beautiful and calm at night. The sky is warm and sunny in the morning.','The sky is','Breeze and air are');

Output:

The sky is beautiful and calm at night

Example #4

Now, we will replace the substring of the particular column of the table with some other substring. Let us fire \dt command to see all the tables present in my database.

Code:

\dt

Output:

fire \dt command

Example #5

Now, let us see the contents by firing the following query statement.

Code:

SELECT * FROM educba;

Output:

PostgreSQL replace 5

Now we will replace the department string’s substring ‘-side language’ to ‘-end technology’ using the following command.

Code:

UPDATE
educba
SET
department = REPLACE (
department,
'-side language',
'-end technology'
);

Output:

PostgreSQL replace 6

As we can see, four rows are updated, but only two of them had that substring. Hence the columns that didn’t have that substring don’t result in any error but are just skipped.

Code:

SELECT * FROM educba;

Output:

PostgreSQL replace 7

In this way, we studied firstly how a single occurrence of the word can be replaced, then multiple occurrences of the word were replaced and finally a substring replacement and table column data substring replacement demonstration with the help of an example. Now we will see how we can replace the strings matching the regular expressions to be replaced by some other string.

The replace() function is available and compatible with the following versions of PostgreSQL:

  • PostgreSQL 9.4
  • PostgreSQL 9.3
  • PostgreSQL 9.2
  • PostgreSQL 9.1
  • PostgreSQL 9.0
  • PostgreSQL 8.4

REGEXP_REPLACE Function

When we want to replace the words matching a particular regular expression to some other word, then we can use REGEXP_REPLACE() function in PostgreSQL. This can be the case when replacing the old phone numbers or email ids that have some default value with some new value.

Syntax:

REGEXP_REPLACE(original_string, regular_expr_pattern, new_sub_string [,option_flags])

  • original_string: This is the source string that contains the words of substrings matching the regular expression that needs to be replaced.
  • regular_expr_pattern: This is the regular expression pattern that will be searched for possible matched substrings to be replaced.
  • new_sub_string: This is the substring with which the matched substrings will be replaced with.
  • option_flags: Many flags are optional and explain the behaviour of the regular expression match comparison. For example,’ means that the comparison should be case-insensitive, g specifies global substitution of the substring that means all occurrences to be replaced and so on.

Example of REGEXP_REPLACE Function

Given below is the example Function:

“This is the first plant that does synthesis.” we want to replace all the words containing the substring ‘is’ to substring ‘demo’. For that, we will use the REGEXP_REPLACE() function, and our query statement will be as follows.

Code:

select regexp_replace('This is first plant that does synthesis.','is','demo','g');

Output:

REGEXP_REPLACE() function

If we had not mentioned the ‘g’ flag and fired the following query.

select regexp_replace('This is first plant that does synthesis.','is','demo','');

Output:

PostgreSQL replace 9

And the only first occurrence of is would have been replaced with the demo.

TRANSLATE() Function

When more that one substring needs to be replaced by the same substring, then the translate() function is used.

Syntax:

TRANSLATE(original_string, set_of_characters, new_set_characters);

  • original_string: This is the source string that contains the set of characters to be replaced.
  • set_of_characters: This is the set of all characters present in the original string that you wish to replace.
  • new_set_characters: This is a set of the characters with which the matched characters will be replaced.

Example of TRANSLATE() Function

Given below is the example of TRANSLATE() Function:

Code:

SELECT TRANSLATE ('The sky is beautiful and calm at night','ky', 'et');

Output:

PostgreSQL replace 10

Conclusion – PostgreSQL replace

We saw about the methods, namely REPLACE(), REGEXP_REPLACE() and TRANSLATE() methods that can be used for string replacement in PostgreSQL while dealing with string manipulations.

Recommended Articles

This is a guide to PostgreSQL replace. Here we discuss the introduction of PostgreSQL replace, REGEXP_REPLACE function and TRANSLATE() function. You may also have a look at the following articles to learn more –

  1. CAST in PostgreSQL
  2. PostgreSQL NOT NULL
  3. PostgreSQL JSON
  4. PostgreSQL Administration
  5. Guide to PostgreSQL Auto Increment
  6. PostgreSQL Trunc() | How to Work?
  7. Learn the PostgreSQL round
Popular Course in this category
PostgreSQL Course (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |  7+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more