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.

SqlData Integrity

Code

snippet
-- 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

FAQ

What relations does the SQL touch?
The references are `padded`, `exact`.