REPLACE() in SQL
Replaces all occurrences of a substring within a string with another substring.
Syntax
Return type
REPLACE() Function Example
What is REPLACE() in SQL?
The REPLACE()
function in SQL replaces all occurrences of a specified substring within a given string with another substring. It is commonly used to clean up text, modify values dynamically, or standardize formatting in database records. This function is supported in most SQL databases, including MySQL, PostgreSQL, SQL Server, and SQLite, though some systems have slight variations in syntax. Unlike SUBSTRING()
or TRIM()
, REPLACE()
does not modify the original data but returns a new string with the specified replacements applied. It is useful for updating text fields, correcting typos, and formatting outputs efficiently.
Parameters:
original_string: The string to perform replacements in
search_string: The substring to find and replace
replacement_string: The string to replace occurrences with
Example Use Cases:
-- Clean phone numbers
-- Format URLs
-- Standardize text
Notes:
Behavior: Replaces all occurrences of the search string, is case-sensitive by default, and removes the search string if replacement_string is empty ('').
Performance Considerations: Multiple replacements can impact performance
Version Info: Core SQL function, supported in all major DBMS
Error Handling:
Error: Returns NULL if any parameter is NULL
Recommendation: Use COALESCE if NULL handling is needed
Supported Databases:
DBMS
Function / Syntax
Example
Behavior with NULL
MySQL
REPLACE()
REPLACE('test', 't', 'p')
Returns NULL
PostgreSQL
REPLACE()
REPLACE('test', 't', 'p')
Returns NULL
SQL Server
REPLACE()
REPLACE('test', 't', 'p')
Returns NULL
SQLite
REPLACE()
REPLACE('test', 't', 'p')
Returns NULL
BigQuery
REPLACE()
REPLACE('test', 't', 'p')
Returns NULL
Snowflake
REPLACE()
REPLACE('test', 't', 'p')
Returns NULL
Athena
REPLACE()
REPLACE('test', 't', 'p')
Returns NULL