// strings reference

SQL collapse multiple spaces

Normalize whitespace: 'a b' becomes 'a b'. Regex does it in one call; SQL Server before 2025 needs the nested-REPLACE idiom or a loop.

カテゴリ
Strings
Returns
string
In this category
75 of 172

構文

REGEXP_REPLACE(s, '\s+', ' ')  -- PostgreSQL: add 'g'

エンジンサポート

エンジンSupportメモ
SQL Server はい REGEXP_REPLACE from SQL Server 2025; nested REPLACE before that
PostgreSQL はい Supported under this name.
MySQL はい Supported under this name.
SQLite はい Supported under this name.
Oracle はい Supported under this name.

例

PostgreSQL

SELECT REGEXP_REPLACE(note, '\s+', ' ', 'g') AS tidy FROM notes;

SQL Server

SELECT LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(note, '  ', ' '), '  ', ' '), '  ', ' '))) AS tidy
FROM notes;  -- three passes handle runs up to 8

MySQL

SELECT REGEXP_REPLACE(note, ' +', ' ') AS tidy FROM notes;

知っておくと便利なこと

  • Regex form: REGEXP_REPLACE(s, '\s+', ' ') collapses tabs, newlines and space runs on Oracle and SQL Server 2025. PostgreSQL replaces only the first match unless you pass 'g' as the fourth argument. On MySQL the literal '\s+' arrives as 's+' because the backslash is a string escape; write '[[:space:]]+' or '\\s+'. Use ' +' for spaces only.
  • The pre-2025 SQL Server idiom is repeated REPLACE(s, ' ', ' '): each pass halves the longest run, so n nested passes handle runs up to 2^n. LTRIM/RTRIM the ends separately.
  • Order matters when cleaning everything: strip newlines and NBSPs first, then collapse, or the collapsed result still hides non-space characters.
  • MySQL before 8.0 has no REGEXP_REPLACE: the nested-REPLACE idiom applies there too.

Questions about Collapsing duplicate spaces

Why are some double spaces still there?

Each nested REPLACE pass halves run lengths: one pass turns 8 spaces into 4, not 1. Add passes until they exceed the longest run you can produce, or use regex.

Does '\s+' include tabs and newlines?

Yes. PostgreSQL, MySQL 8+, Oracle and SQL Server 2025 all support the \s class, but on MySQL the backslash must be doubled in the literal ('\\s+'), or use [[:space:]]. Use ' +' when spaces alone should collapse.

How do I collapse spaces on SQL Server?

On 2025, REGEXP_REPLACE(s, ' +', ' '). Before that, the nested REPLACE(s, ' ', ' ') idiom plus LTRIM/RTRIM, or a WHILE loop for unbounded runs. Keep it in a view or function so the idiom lives once.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.