Lesson

MySQL REPLACE() Function

10 min reading
Free Course

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 delete from_str).
  • Return value: Updated string, or NULL if any argument is NULL.

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() or LIKE, MySQL's REPLACE() performs a case-sensitive match for from_str even on _ci columns. Standardize casing or use REGEXP_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_str is NULL, REPLACE('abc', 'b', NULL) returns NULL, 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'.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum