Strings

REPLACE

Replaces every occurrence of one piece of text in a string with another.

Syntax

REPLACE(<text>, <from>, <to>)

Searches the text for a substring and replaces each occurrence, not just the first. To remove a substring completely, replace it with an empty string ''. Often used to clean up data, for example to remove spaces from phone numbers or swap an old domain in links.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Replace a word
SELECT REPLACE('I love MySQL', 'MySQL', 'PostgreSQL') AS result;
result
I love PostgreSQL
Every occurrence, not just the first
SELECT REPLACE('a-b-c-d', '-', ', ') AS result;
result
a, b, c, d
Phone numbers without spaces
SELECT name, phone,
REPLACE(phone, ' ', '') AS compact_phone
FROM employees;
namephonecompact_phone
Emma+44 7700 900123+447700900123
LiamNULLNULL
Olivia+44 7700 900456+447700900456
Noah+44 7700 900789+447700900789
SophiaNULLNULL

Watch out

Case matters: REPLACE('Hello', 'hello', 'Hi') replaces nothing. To ignore case — REGEXP_REPLACE(<text>, 'hello', 'Hi', 'gi').

It replaces a whole substring, not individual characters. To remove several different characters at once, use TRANSLATE: TRANSLATE('+44 (0) 7700', '() ', '') gives +4407700.

If any argument is NULL, the result is NULL too: REPLACE('abc', 'b', NULL).

Learn more in the course