SQL remove non-breaking spaces
Data pasted from Excel, web pages and PDFs carries U+00A0. It renders as a space, fails string comparisons, and TRIM will not touch it.
- 类别
- Strings
- Returns
string- In this category
- 40 of 172
语法
REPLACE(s, CHAR(160), ' ')
引擎支持
| 引擎 | Support | 备注 |
|---|---|---|
| SQL Server | 是 | Supported under this name. |
| PostgreSQL | 是 | Supported under this name. |
| MySQL | 是 | Supported under this name. |
| SQLite | 是 | Supported under this name. |
| Oracle | 是 | Supported under this name. |
示例
SQL Server
SELECT REPLACE(name, NCHAR(160), ' ') AS fixed FROM names;
MySQL
SELECT REPLACE(name, CHAR(0xC2A0 USING utf8mb4), ' ') AS fixed FROM names;
Oracle
SELECT REPLACE(name, CHR(160), ' ') AS fixed FROM names;
值得了解
- Default TRIM removes only ordinary spaces, so U+00A0 survives it on every engine. It goes only if you name it in a character-set trim or REPLACE it.
- MySQL trap: CHAR(160) is a single binary byte, and CHAR(160 USING utf8mb4) is NULL because 0xA0 alone is not valid UTF-8. Use the two UTF-8 bytes: CHAR(0xC2A0 USING utf8mb4).
- SQL Server: use NCHAR(160) against nvarchar data; CHAR(160) depends on the varchar codepage.
- Diagnose with bytes, not eyes: Oracle DUMP(col, 16), PostgreSQL encode(convert_to(col, 'utf8'), 'hex') and MySQL HEX(col) show the NBSP as c2a0 in UTF-8 data.
Questions about Removing non-breaking spaces
Why does my WHERE clause miss values that look identical?
One side holds U+00A0 instead of a space: same pixels, different code point, so = fails. Replace the NBSP with ' ' on both sides, or clean on write.
Why did TRIM not remove it?
TRIM strips spaces (or an explicit character set). The non-breaking space is a different character; pass it to the character-set form or REPLACE it.
How do I find how many are lurking?
Compare lengths before and after removing them: LEN(col) - LEN(REPLACE(col, NCHAR(160), '')) on SQL Server counts the NBSPs in each value.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.