Replace multiple patterns in one SQL expression
Phone numbers arrive with parentheses, dashes and spaces. Delete every punctuation variant in one expression.
The task
Before dialing or joining on phone numbers, remove parentheses, dashes and spaces in one go.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT REPLACE(REPLACE(REPLACE(REPLACE(phone_raw, '(', ''), ')', ''), '-', ''), ' ', '') AS phone_clean
FROM contacts;
Как это работает
Each REPLACE strips one pattern, applied inside-out. This is fully portable because REPLACE exists on every engine, and the pattern set is explicit in the code. It gets unwieldy past four or five patterns; that is where TRANSLATE helps for single characters, though each engine treats a missing replacement character differently (see the variants).
Variations
PostgreSQL: TRANSLATE deletes characters with no partner
PostgreSQLSELECT TRANSLATE(phone_raw, '()- ', '') AS phone_clean
FROM contacts;
Oracle: keep one mapped character, or '' (NULL) makes the result NULL
OracleSELECT TRANSLATE(phone_raw, '#()- ', '#') AS phone_clean
FROM contacts;
Questions that come up
Why does the TRANSLATE variant only handle single characters?
TRANSLATE maps each character in the second argument to the character at the same position in the third; it works on characters, not substrings, so it cannot target a sequence like 'ext.'. PostgreSQL and Oracle delete characters that have no partner. SQL Server 2017+ requires both lists to be the same length, so it can only substitute (for example to spaces, then one REPLACE), and MySQL and SQLite have no TRANSLATE.
Keep reading
Related on SQLly
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.