
187 views
MySQL Replace
The MySQL REPLACE()
function is used to replace all occurrences of a specified substring within a given string with another substring. It’s commonly used to perform string replacements in text columns.
The basic syntax of the REPLACE()
function is as follows:
REPLACE(original_string, substring_to_replace, replacement_string)
Here’s a breakdown of each part of the function:
original_string
: This is the string in which you want to perform replacements.substring_to_replace
: This is the substring you want to find and replace within theoriginal_string
.replacement_string
: This is the string that will replace the occurrences ofsubstring_to_replace
.
Here are some examples of how to use the REPLACE()
function in MySQL:
- Replace all occurrences of ‘apple’ with ‘orange’ in a text column named
fruit
:
SELECT REPLACE(fruit, 'apple', 'orange') FROM fruit_table;
- Update a table by replacing ‘www’ with ‘blog’ in a column named
website_url
:
UPDATE websites
SET website_url = REPLACE(website_url, 'www', 'blog')
WHERE website_id = 123;
- Create a calculated column that replaces ‘-‘ with ‘/’ in a date format:
SELECT event_date, REPLACE(event_date, '-', '/') as formatted_date
FROM events;
- Replace double spaces with single spaces in a text column:
SELECT REPLACE(description, ' ', ' ') FROM text_data;
The REPLACE()
function is particularly useful when you need to modify the contents of text data within your SQL queries. It can be applied in both SELECT
statements for querying and in UPDATE
statements to modify existing data. It simplifies the process of making string substitutions within the database.