CHAR Blank Padding Semantics
CHAR(n) pads stored values with spaces and ignores trailing spaces in comparisons and length(), while VARCHAR(n) keeps every byte.
Code
-- char(n) 定长:存储右侧补空格到 n;比较、length、拼接前都剥掉尾部空格
-- varchar(n)/text:原样存储,空格参与比较与长度
SELECT
'ab'::char(4) = 'ab '::char(4) AS char_ignores_trailing, -- true
'ab'::varchar(4) = 'ab '::varchar(4) AS varchar_counts_spaces, -- false
length('ab '::char(4)) AS char_length_still_2, -- 2
octet_length('ab'::char(4)) AS char_octet_stripped, -- 2
'ab'::char(4) || 'x' AS concat_strips_pad, -- abx
'ab'::varchar(4) || 'x' AS varchar_concat; -- ab x
-- 唯一约束视角:char 上 'ab' 与 'ab ' 视为重复;varchar 上是两个不同键
CREATE TABLE padded (code CHAR(4) UNIQUE);
CREATE TABLE exact (code VARCHAR(4) UNIQUE);
INSERT INTO padded VALUES ('ab'), ('ab '); -- 第二行触发 unique 冲突
INSERT INTO exact VALUES ('ab'), ('ab '); -- 两行都成功,空格参与比较How the snippet works
SELECT / INSERT / CREATE statements share the script, touching padded and exact.
Mechanically, the statements are built from: UNIQUE constraints that keep duplicate values out.
Applying it
The padded table is the working surface here.
Statements that matter
INSERT INTO padded VALUES ('ab'), ('ab '); -- 第二行触发 unique 冲突
INSERT INTO exact VALUES ('ab'), ('ab '); -- 两行都成功,空格参与比较
CREATE TABLE exact (code VARCHAR(4) UNIQUE);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.DSN Connection String ParserParse PostgreSQL, MySQL, Redis, MongoDB, and AMQP DSN URLs locally with masked credentials, multi-host support, default ports, and SSL/pool inspection.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- What relations does the SQL touch?
- The references are `padded`, `exact`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.