// SQL snippet

Normalize whitespace in SQL

User-typed text arrives with double spaces, leading and trailing blanks. Normalize it before you store or compare it.

Main statement
All engines

The task

Notes, addresses and names typed by people collect double spaces and stray leading blanks. Comparing or grouping that text fails until you normalize it.

The snippet

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

All engines
SELECT
    TRIM(REPLACE(REPLACE(REPLACE(note, ' ', '<>'), '><', ''), '<>', ' ')) AS clean_note
FROM notes;

Como funciona

The trick replaces every space with a marker (<>), then deletes marker pairs (><), then turns the surviving marker back into one space. Any run of spaces collapses to a single space in three plain REPLACE calls, no regex needed. TRIM then removes what is left at the ends. TRIM needs SQL Server 2017 or later; older versions use LTRIM(RTRIM(...)). Pick a marker that cannot occur in the data.

Variations

PostgreSQL: regex (the 'g' flag replaces every match)

PostgreSQL
SELECT TRIM(REGEXP_REPLACE(note, '\s+', ' ', 'g')) AS clean_note
FROM notes;

MySQL 8, Oracle, SQL Server 2025: regex (replaces every match by default)

SQL Server MySQL Oracle
SELECT TRIM(REGEXP_REPLACE(note, '[[:space:]]+', ' ')) AS clean_note
FROM notes;

Questions that come up

Does this handle tabs and line breaks too?

No. The portable version only collapses spaces. To fold tabs, carriage returns and line feeds into single spaces first, replace them with a space before the triple-REPLACE, or use a regex variant: \s and [[:space:]] match tabs and line breaks as well as spaces. SQLite has no built-in REGEXP_REPLACE.

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.