MySQL REPLACE() Function
MySQL REPLACE() Function
The REPLACE() string function finds every occurrence of a target substring inside a string and swaps it with replacement text. Note that this is a string expression function, distinct from the REPLACE INTO table-write command.
Syntax
REPLACE(str, from_str, to_str)
- str: The original string to edit.
- from_str: The exact substring to search for and remove.
- to_str: The replacement string (pass
''to deletefrom_str). - Return value: Updated string, or
NULLif any argument isNULL.
REPLACE() replaces all matches in one pass from left to right without re-scanning newly inserted characters.
Practical Example
Suppose demo_products migrated from legacy SKU separators ('-') to underscores ('_') and updated old 'USB2' labels inside descriptions.
SELECT
product_id,
sku,
REPLACE(sku, '-', '_') AS clean_sku,
REPLACE(description, 'USB2', 'USB-C') AS updated_desc
FROM demo_products
ORDER BY product_id;
| product_id | sku | clean_sku | updated_desc |
|---|---|---|---|
| 1 | EL-HUB-01 | EL_HUB_01 | Fast USB-C Dock |
| 2 | EL-CBL-02 | EL_CBL_02 | Braided usb2 Cable |
| 3 | NULL | NULL | NULL |
Look closely at row 2: 'Braided usb2 Cable' did not change because REPLACE() matched 'USB2' case-sensitively!
Common Mistakes & NULL Behavior
- REPLACE() is always case-sensitive: Unlike
LOCATE()orLIKE, MySQL'sREPLACE()performs a case-sensitive match forfrom_streven on_cicolumns. Standardize casing or useREGEXP_REPLACE(col, 'usb2', 'USB-C', 1, 0, 'i')in MySQL 8.0+ for case-insensitive swaps. - Empty from_str does nothing:
REPLACE('abc', '', 'X')returns'abc'unchanged; it does not insert'X'between characters. - Any NULL argument wipes out the result: If
to_strisNULL,REPLACE('abc', 'b', NULL)returnsNULL, not'ac'.
Frequently Asked Questions
How do I delete a substring with REPLACE()?
Pass an empty string '' as to_str, for example REPLACE(phone, '-', '') to strip all hyphens.
Does REPLACE() modify the stored table row?
In a SELECT query, it only transforms the output. Wrap it inside UPDATE demo_products SET sku = REPLACE(sku, '-', '_') to save changes to disk.
What happens with overlapping matches like REPLACE('aaa', 'aa', 'b')?
MySQL scans left to right non-overlapping, turning 'aaa' into 'ba'.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.