What is Replace in SQL and How to Use Replace() Function [Updated] (2024)

While managing an extensive database as an data analyst, you might sometimes want to replace a string data field substring with another. One option you have is to delete the record and then add it with a new value. That’s the basic way that pops into everyone’s mind. But ‘replace in SQL’ provides another efficient way to do this.

What is Replace in SQL?

Replace in SQL is a built-in function that allows you to replace all the incidents of a substring within a specified string with a new substring. Thus, whenever you want to replace something like a dead link or a product name, the replace() function is the way to go. The basic syntax of replace in SQL is:

REPLACE(String, Old_substring, New_substring);

In the syntax above:

  • String: It is the expression or the string on which you want the replace() function to operate.
  • Old_substring: It is the substring that you want to look for in the string and replace.
  • New_substring: It is the new substring that you want to include in place of the Old_substring.

Note: The strings that you include in the replace() function are case-sensitive. Thus, always make sure to use the exact string that you want to search for and replace.

Your Data Analytics Career is Around The Corner!

Data Analyst Master’s ProgramExplore Program

What is Replace in SQL and How to Use Replace() Function [Updated] (1)

Let’s look at an example to better understand the syntax of replace in SQL and how it works.

SELECT

REPLACE('This is Java Tutorial', 'Java', 'SQL');

Output:

What is Replace in SQL and How to Use Replace() Function [Updated] (2)

As you can see in the output, the substring ‘Java’ was replaced by ‘SQL.’ Thus, the replace function will search for Java and replace it with SQL. This was a simple use case with only a single occurrence of the Old_substring. Let’s look at another example where there are multiple occurrences of the Old_substring and replace them with the New_substring.

SELECT

REPLACE('This tea store serves the best tea from a teapot', 'tea', 'coffee');

Output:

What is Replace in SQL and How to Use Replace() Function [Updated] (3)

As you can see, all the occurrences of the substring ‘tea’ were replaced with the New_substring ‘coffee,’ even if the substring was attached to other characters as with the word ‘teapot.’ But if you pass an Old_substring that is not present in the string expression, the SQL replace() function will return the string as it is. Let’s look at an example for that too.

SELECT

REPLACE("Welcome to Simplilearn's SQL Tutorials", 'Sql', 'Java');

Output:

What is Replace in SQL and How to Use Replace() Function [Updated] (4)

Since the replace() function search is case sensitive, it will not consider ‘Sql’ the same as ‘SQL.’ Thus, for the server, there is no SQL in the original string. Hence, it will simply return the exact string without making any changes.

Your Data Analytics Career is Around The Corner!

Data Analyst Master’s ProgramExplore Program

What is Replace in SQL and How to Use Replace() Function [Updated] (5)

How to Use Replace in SQL With the UPDATE Statement?

In this article, you have seen some examples of using replace in SQL with literal strings. However, in SQL, you will work with tables and databases. So let’s move to use the SQL replace() function along with the UPDATE statement to update data in a table.

A real-world example can be managing the Customers' table of global clients. Suppose you have entered the wrong country code in the contact list and want to replace it with the correct code for all the country’s contacts. That’s where you can use replace in SQL. Before getting into anything, create the Customers table using the CREATE TABLE command and insert some values using the INSERT INTO command.

-- Creating the table

CREATE TABLE Customers(

C_ID int PRIMARY KEY,

C_FirstName VARCHAR(20) NOT NULL,

C_LastName VARCHAR(20) NOT NULL,

Country VARCHAR(20) NOT NULL,

Contact_No NVARCHAR(15) UNIQUE,

Email_ID NVARCHAR(35)

);

-- Inserting some values

INSERT INTO Customers VALUES (1, 'Aakash', 'Roy', 'India', '+91 861.543.1240', 'ar.com');

INSERT INTO Customers VALUES (2, 'Adam', 'Frip', 'USA', '+2 651.283.1942', 'af.com');

INSERT INTO Customers VALUES (3, 'David', 'Hemsworth', 'France', '+33 527.535.4569', 'dh.com');

INSERT INTO Customers VALUES (4, 'Rahul', 'Chopra', 'India', '+91 935.283.9212', 'rc.com');

INSERT INTO Customers VALUES (5, 'Chris', 'Martin', 'USA', '+2 726.835.9625', 'dm.com');

INSERT INTO Customers VALUES (6, 'Charles', 'Johnson', 'France', '+33 650.239.5647', 'cj.com');

INSERT INTO Customers VALUES (7, 'George', 'Austin', 'India', '+91 932.751.6583', 'ga.com');

-- Fetching the results

Select * FROM Customers;

Output:

What is Replace in SQL and How to Use Replace() Function [Updated] (6)

If you would have noticed, this demo incorrectly entered the country code for the USA clients to be ‘+2’ instead of ‘+1.’ Let’s use replace in SQL along with the UPDATE statement to correct this error.

UPDATE Customers

SET

Contact_No = REPLACE(Contact_No, '+2', '+1');

-- Fetching the outcome

SELECT * FROM Customers;

Output:

What is Replace in SQL and How to Use Replace() Function [Updated] (7)

As you can see, all the Contact_No data with ‘+2’ were replaced with ‘+1’. Thus, the mistakes in all the fields were quickly taken care of with a single line of command with the use of replace in SQL. However, this was a small table. But while working with large tables where the number of affected rows is more, it is essential to check if the function executes as expected. You can check it with the WHERE clause’s help to first apply it in a single row. Now, use the WHERE clause to replace the ‘.’ character in the Contact_No column with ‘-’ for a row with C_ID = 5 before applying it to the entire table.

UPDATE Customers

SET

Contact_No = REPLACE(Contact_No, '.', '-')

WHERE

C_ID = 5;

-- Fetching the outcome

SELECT * FROM Customers

WHERE C_ID = 5;

Output:

What is Replace in SQL and How to Use Replace() Function [Updated] (8)

Now that you know it works as expected, you can apply it to the entire table by removing the WHERE clause.

Become The Highest-Paid Business Analysis Expert

With Business Analyst Master's ProgramExplore Now

What is Replace in SQL and How to Use Replace() Function [Updated] (9)

UPDATE Customers

SET

Contact_No = REPLACE(Contact_No, '.', '-');

-- Fetching outcome

Select * FROM Customers;

Output:

What is Replace in SQL and How to Use Replace() Function [Updated] (10)

As you can see, all the ‘.’ characters in the Contact_No field were replaced with the ‘-’ character. One more thing worth noting is that you have passed Contact_No as a column and not as a string expression, which is a simple mistake to make. Thus, don’t use single inverted commas (‘’) while passing the first argument in the SQL replace() function. Let’s see what happens if you pass the first expression as a column. In the example below, you will try changing the substring ‘com’ from Email_ID to ‘simplilearn.org.’ First, you have to pass Email_ID as a literal string and later as a column and see the results.

UPDATE Customers

SET

Email_ID = REPLACE('Email_ID', 'com', 'simplilearn.org');

SELECT * FROM Customers;

Output:

What is Replace in SQL and How to Use Replace() Function [Updated] (11)

As you can see in the output, instead of changing the substring, the replace() function changed the entire column’s field to ‘Email_ID’ as you had passed it as a literal string and not a column. If instead of using it as a string expression, you remove the inverted commas and give it as a column. Then it will work as expected. Let’s look at the output for that.

UPDATE Customers

SET

Email_ID = REPLACE(Email_ID, 'com', 'simplilearn.org');

Select * FROM Customers;

Output:

What is Replace in SQL and How to Use Replace() Function [Updated] (12)

As expected, this time, the SQL replace() function changed the ‘org’ substring in the Email_ID column from the Customers table to ‘simplilearn.org.’

What is Replace in SQL and How to Use Replace() Function [Updated] (2024)
Top Articles
Company Culture Netflix
View-only mode
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Pearson Correlation Coefficient
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Nfsd Web Portal
Selly Medaline
Latest Posts
Article information

Author: Aron Pacocha

Last Updated:

Views: 5899

Rating: 4.8 / 5 (68 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Aron Pacocha

Birthday: 1999-08-12

Address: 3808 Moen Corner, Gorczanyport, FL 67364-2074

Phone: +393457723392

Job: Retail Consultant

Hobby: Jewelry making, Cooking, Gaming, Reading, Juggling, Cabaret, Origami

Introduction: My name is Aron Pacocha, I am a happy, tasty, innocent, proud, talented, courageous, magnificent person who loves writing and wants to share my knowledge and understanding with you.