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
Three Benefits of a Holistic Financial Planning Approach
8 Tips for Finding a Job During a Recession | FlexJobs
I brought the best part of Windows to my MacBook and it gave me a huge productivity boost
Busted Newspaper Mcpherson Kansas
Cars for Sale by Owner in Shreveport, LA
K-Active – Jetzt kaufen bei SVG
2019 Nissan Altima Wheel Torque Specs
R/Honkaistarrail
YouTube Sperren mit Proxy umgehen - So geht's 2024 – PrivacyTutor
Marcus Samuelsson Daughter Zoe
Ursa Major Neighbor Crossword Clue
[Top 5] Enter The Gungeon Best Synergies
What is the difference between a T-bill and a T note?
184€ Flug Frankfurt am Main - Lahore - Günstige Flüge von Frankfurt am Main nach Lahore - KAYAK
Rent A Center Entertainment Center
Memphis Cars For Sale Craigslist
Poe Reave
Hombre Busca Hombre Houston
mikroC PRO for PIC | Mikroe
Bustednewspaper Smith County Tx
Theophylline: MedlinePlus Drug Information
27L1576
What Year Did Cim Open Their Ipo
Teksystems Time And Expense
Craigslist Mendocino Coast
Sea Guini Dress Code
Nepg Live Scoring
Tf2 Cosmetics Tester
Now is The Perfect Time for Bethesda to Remake Morrowind
Dental Injuries 14420
Deer Shed Clover Sc
Kickflip Seeds
Craigslist.org Knoxville
Marketplace Palm Coast
Online Finance & Accounting Courses
Graduate Research Employment Program - Biomedical Ethics - Limited Tenure at Mayo Clinic
New Jersey Motor Vehicle Commission Elizabeth Fotos
45 Arch Street Akron Ohio
Www.mygoodtogo
Target hiring On - Demand Guest Advocate in Port Chester, NY | LinkedIn
R/Mp5
My Time At Portia Valve
Toro 21 Front Mount Dethatcher
Rawdogriley
Jess Bush Wikifeet
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
What is "Brrr skibidi dop dop / dom dom yes yes"? Memes, explanation, meaning, definition - Bedeutung Online
10 Competências da SMMA de Foz do Iguaçu - material14832 - Legislação
BEX Holiday Homes (Las Palmas de Gran Canaria): Alle Infos zum Hotel
Horseshoe Indiana Entries
Compass | History, Uses & Types
Directions To Cvs Pharmacy
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.