// SQL snippet

Remove all whitespace from a string in SQL

Phone numbers, account codes and search keys should not contain blanks at all. Clean them in one expression.

Main statement
All engines

The task

Imported values contain blanks everywhere. Before matching them against clean reference data, delete every space (and, where the engine allows, tab and break characters).

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT REPLACE(phone_raw, ' ', '') AS phone_clean
FROM contacts;

仕組み

REPLACE simply deletes each space. It exists on every engine, so the basic form is fully portable. When you also need tabs, carriage returns and line feeds gone, chain more REPLACE calls with each engine's character function: CHAR(n) on SQL Server, MySQL and SQLite, CHR(n) on PostgreSQL and Oracle.

Variations

SQL Server: spaces, tabs, CR and LF

SQL Server
SELECT REPLACE(REPLACE(REPLACE(REPLACE(phone_raw, ' ', ''), CHAR(9), ''), CHAR(13), ''), CHAR(10), '') AS phone_clean
FROM contacts;

PostgreSQL and Oracle: spaces, tabs, CR and LF

PostgreSQL Oracle
SELECT REPLACE(REPLACE(REPLACE(REPLACE(phone_raw, ' ', ''), CHR(9), ''), CHR(13), ''), CHR(10), '') AS phone_clean
FROM contacts;

Questions that come up

Why not just compare after TRIM?

TRIM only removes characters at the two ends. An interior blank like '555 0100' still fails to match '5550100', so delete interior blanks too when the target format has none.

Keep reading

// snippets are better with a schema brain

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.