Back to String Functions

Mysql - REPLACE() Function

The `REPLACE()` function in MySQL is used to replace all occurrences of a specified substring within a string with another substring. This function is useful for modifying string values by replacing parts of them with new values.

Syntax

REPLACE(string, search_string, replace_string)

Parameters:
  • string: The original string where you want to perform the replacement.
  • search_string: The substring to search for within the string.
  • replace_string: The substring to replace the search_string with.
How It Works:
  • If search_string is found within the string, it is replaced with replace_string.
  • If search_string is not found, the string remains unchanged.
  • This function is case-sensitive.
Example 1: Basic Usage

SELECT REPLACE('Hello World', 'World', 'MySQL');

Output:

Hello MySQL

Example 2: Replacing Part of a Column Value

Let's consider an example using the `REPLACE()` function with an `employees` table. The `REPLACE()` function replaces all occurrences of a specified string with another string.

idfirst_namelast_nameposition
1JohnDoeSoftware Engineer
2JaneSmithProject Manager
3EmilyJohnsonBusiness Analyst
4MichaelBrownSoftware Engineer
5JessicaWilliamsProduct Manager

Now, if we want to replace the term "Manager" with "Lead" in the `position` column.

SELECT id, first_name, last_name, position, REPLACE(position, 'Manager', 'Lead') AS new_position FROM employees;

This query will return:

idfirst_namelast_namepositionnew_position
1JohnDoeSoftware EngineerSoftware Engineer
2JaneSmithProject ManagerProject Lead
3EmilyJohnsonBusiness AnalystBusiness Analyst
4MichaelBrownSoftware EngineerSoftware Engineer
5JessicaWilliamsProduct ManagerProduct Lead

The `REPLACE()` function replaces "Manager" with "Lead" in the `position` column.

Aspirant's Home is an innovative educational and career development platform designed to empower individuals in achieving their academic and professional aspirations.
Terms of Use   About Us   Privacy Policy