← 中文资源

简体中文版本

varchar 长度上限与 text 的取舍

varchar(n) 在写入时强制上限、text 无上限;业务上限放 CHECK 约束更合适:改规则只改约束不动列类型,超长与超限的报错信息也各自明确。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 labels。 具体组合了这些手段:ORDER BY 固定了输出顺序;CHECK 约束在写入时就把越界值拒之门外;必填列上的 NOT NULL 限定。

常见问题

这个脚本里出现了哪些表?

labels。

核心语句

CREATE TABLE labels (
    code    varchar(8) NOT NULL,    -- hard cap in the column type; longer values are rejected outright
    title   text       NOT NULL,    -- no cap
    summary text       NOT NULL,    -- business cap lives in a CHECK
    CONSTRAINT summary_cap CHECK (char_length(summary) <= 200)
);
INSERT INTO labels VALUES ('ok2', 'also fine', repeat('x', 200));  -- exactly 200, accepted
SELECT code, char_length(summary) AS summary_len
FROM labels
ORDER BY code;

代码示例

-- varchar(n) limits at write time; text has no length limit
CREATE TABLE labels (
    code    varchar(8) NOT NULL,    -- hard cap in the column type; longer values are rejected outright
    title   text       NOT NULL,    -- no cap
    summary text       NOT NULL,    -- business cap lives in a CHECK
    CONSTRAINT summary_cap CHECK (char_length(summary) <= 200)
);

INSERT INTO labels VALUES ('ok', 'fine', 'short enough');
INSERT INTO labels VALUES ('ok2', 'also fine', repeat('x', 200));  -- exactly 200, accepted

-- the two failures take different gates:
-- INSERT INTO labels VALUES ('way too long', 'x', 'x');
--   -> ERROR: value too long for type character varying(8)
-- UPDATE labels SET summary = repeat('x', 201);
--   -> ERROR: new row for relation "labels" violates check constraint "summary_cap"

SELECT code, char_length(summary) AS summary_len
FROM labels
ORDER BY code;