REPLACE example
We want a display version of the product name in which spaces become hyphens:
SELECT name,
REPLACE(name, ' ', '-') AS name_with_hyphens
FROM products
ORDER BY id
LIMIT 6;What to look for: For example, "Pro Laptop" is shown as "Portátil-Pro". The function returns a calculated string; it does not change the original name stored in products.
Check the result with small data
The paths contain spaces that we want to replace with hyphens.
WITH routes(text_value) AS (
VALUES ('basic sql'),('advanced sql')
)
SELECT REPLACE(text_value, ' ', '-') AS route
FROM routes ORDER BY route;| route |
|---|
| advanced-sql |
| basic-sql |
REPLACE returns new text; it does not run an UPDATE or change the stored text.
Check your understanding: What would you change to replace only «sql» with «course»?
Show answer
The search and replacement arguments: REPLACE(text_value, 'sql', 'course'). You would get "course basico" and "course avanzado".
How REPLACE is used
The search matches characters according to the engine's rules and settings. If the substring does not appear, the text comes back unchanged.
Common mix-ups with REPLACE
Confusing the function with a write statement
Some engines have a statement or variant called REPLACE for inserting or replacing rows. It is not the same as the three-argument text function.
SELECT REPLACE(name, ' ', '-')
FROM products;Always check whether you are using an expression inside SELECT or a statement that can modify data.
A literal substitution does not validate or interpret the text
The function replaces matching text, not concepts. Removing hyphens from a code can be a well-defined normalisation; removing every dot from an amount written with separators can change its value or make it ambiguous. Settle the source format before transforming it. It is not a regular expression or a semantic search function either.
Test a string with one match, several matches and none. Also check whether case matters: the comparison rules of the function and the engine may not match those of a text filter you already use. If the input is null, do not expect an empty string to appear; keep or handle that missing value explicitly.
SELECT REPLACE(...) only shows a calculated version. Saving the substitution requires a write, and it is wise to preview the original next to the new value first. A transformation can make two previously different codes identical and cause a conflict with a unique key. Check for that collision before updating a whole column.
Technical questions: SQLite: scalar functions (opens in a new tab).