SQL Server REPLACE() Function

The REPLACE() function in SQL Server is used to substitute all occurrences of a specific substring within a string with a new substring. It's a fundamental string manipulation function.



REPLACE(): Definition and Usage

REPLACE() is a powerful tool for modifying text data. It's particularly useful for standardizing text, correcting typos, or making targeted changes to strings. Unlike some string functions, REPLACE() is case-sensitive. For more precise edits at specific string positions, consider using STUFF().

Syntax

Syntax

REPLACE(string, old_string, new_string)
      

Parameter Values

Parameter Description
string The original string where the replacement will take place. This is required.
old_string The substring to be replaced. This is required.
new_string The substring that will replace all occurrences of old_string. This is required.

Examples

Replacing a Single Character

This example replaces all occurrences of the letter 'T' with 'M' in the string 'SQL Tutorial'.

Syntax

SELECT REPLACE('SQL Tutorial', 'T', 'M');
      
Output

SQL Muutorial
      

Replacing a Substring

This replaces 'SQL' with 'HTML'.

Syntax

SELECT REPLACE('SQL Tutorial', 'SQL', 'HTML');
      
Output

HTML Tutorial
      

Replacing a Character (Case-Sensitive)

Note that this is case-sensitive; only lowercase 'a' is replaced.

Syntax

SELECT REPLACE('ABC abc ABC', 'a', 'c');
      
Output

ABC cbc ABC