Replace String in SQL Server
Last Updated :
23 Jul, 2025
In SQL Server, manipulating data from a table and applying functions to modify values dynamically is a common task. One such example involves replacing parts of strings, such as email domains.
This content demonstrates how string replacement can be applied to a dataset that includes employee information such as name, salary, city, and email address.
Replacing String Values in SQL Server
- When we need to update or replace any string value in a table in SQL Server, we can use various methods.
- Below are examples demonstrating how to replace a part of a string using the
REPLACE() function in SQL Server.
Example 1: Replacing a String in a Variable
In this example, we will replace a part of a string stored in a variable with a new string using the REPLACE() function.
DECLARE @String_Value varchar(50)
SET @String_Value = 'This provides free and excellent knowledge on SQL Server.'
SELECT REPLACE(@String_Value, 'This', 'GeeksforGeeks');
Output:
GeeksforGeeks provides free and excellent knowledge on SQL Server.
Example 2: Replacing Strings in a Table
Consider the following table named geek_demo:
Example 3: Replacing a String in a SELECT Statement
In this example, we will replace the domain of email addresses from 'xyz.com' to 'gfg.org' while selecting data from the geek_demo table using the REPLACE() function.
SELECT [Name], [Salary], [City], [email],
REPLACE([email], 'xyz.com', 'gfg.org') AS [New EmailID]
FROM [geek_demo];
Output:
Example 4: Replacing Strings in an UPDATE Statement
To update the email addresses in the geek_demo table, we can use the REPLACE() function inside an UPDATE statement:
UPDATE [geek_demo]
SET [email] = REPLACE([email], 'xyz.com', 'gfg.org');
Result:
(8 row(s) affected)
Output:
Conclusion
Modifying string values in a dataset is an essential skill when working with SQL Server. By applying functions like REPLACE(), you can efficiently update strings such as email addresses, which may be necessary when changing domain names or correcting typos.
Explore
Basics
Queries & Operations
SQL Joins & Functions
Data Constraints & Aggregate Functions
Advanced SQL Topics
Database Design & Security