Varchar Length Limit Versus Text

varchar(n) rejects overlong values at write time while text stays unlimited; business caps belong in a CHECK on char_length, not the column type.

SqlData Integrity

Code

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

How it works

SELECT / INSERT / CREATE statements share the script, touching labels.

Breaking the statements into their working parts: an ORDER BY that fixes the output order; a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns.

Putting it to use

The labels table is the working surface here.

Core lines

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;

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`labels`.