SQL replace
Created By: chatGPT
SQL provides a function called
REPLACE
that allows you to substitute occurrences of a specified string within a column's value. This is particularly useful for cleaning up data or modifying strings for various purposes. The syntax for the REPLACE
function is as follows:`REPLACE(original_string, search_string, replacement_string)`
In this syntax:
- original_string: The string to be searched.
- search_string: The substring to be found within the original string.
- replacement_string: The substring that will replace the search_string.
The function returns a new string with all instances of the search_string replaced by the replacement_string.
Here is a practical example. Suppose you have a table named
This command updates the employees
with a column called email
. Let's say you want to replace all instances of '@oldcompany.com' with '@newcompany.com'. You could use the following SQL statement:UPDATE employees
SET email = REPLACE(email, '@oldcompany.com', '@newcompany.com');
email
column for every row in the employees
table, ensuring that every instance of the old email domain is replaced with the new one. It's a straightforward yet powerful way to perform mass updates on text values in a database.