SQL CHAR padding and string comparison
Blank-padded types and PAD SPACE collations make 'abc' and 'abc ' compare equal, except in LIKE, and except on modern MySQL collations.
- 类别
- Strings
- Returns
string- In this category
- 68 of 172
语法
'abc' = 'abc ' -- true under PAD SPACE, false under NO PAD
引擎支持
| 引擎 | 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. |
示例
PostgreSQL
SELECT 'abc'::char(5) = 'abc ' AS char_eq, -- true
'abc' = 'abc ' AS text_eq; -- false
SQL Server
SELECT IIF('abc' = 'abc ', 1, 0) AS eq, IIF('abc' LIKE 'abc ', 1, 0) AS like_;
-- 1, 0
MySQL
SELECT 'abc' = 'abc ' COLLATE utf8mb4_general_ci AS pad_space,
'abc' = 'abc ' COLLATE utf8mb4_0900_ai_ci AS no_pad;
-- 1, 0
值得了解
- CHAR(n) values are blank-padded on storage; SQL Server and PostgreSQL comparisons ignore the padding, so char equality is insensitive to trailing spaces.
- MySQL collations differ: legacy utf8mb4_general_ci is PAD SPACE ('abc' = 'abc ' is true), while utf8mb4_0900_* collations are NO PAD (false). Same server, different answers per collation.
- SQL Server: = ignores trailing spaces but LIKE does not; 'abc' = 'abc ' is 1 while 'abc' LIKE 'abc ' is 0.
- PostgreSQL: varchar comparisons are exact ('abc' = 'abc ' is false); only the bpchar (char) type trims for comparison.
Questions about CHAR padding and comparisons
Why does = ignore trailing spaces but LIKE does not?
SQL Server's equality for padded types applies ANSI padding rules; LIKE is a pattern match over the actual characters, including trailing spaces. RTRIM before LIKE when it matters.
What is PAD SPACE?
A collation property that makes comparisons skip trailing spaces. MySQL 8's 0900 collations dropped it (NO PAD), so equality got stricter when upgrading.
Should I use CHAR for fixed-length codes?
Rarely. The padding behaviour leaks into comparisons and concatenations. VARCHAR plus a CHECK or trim-on-write is more predictable across engines.
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.