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.
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;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
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.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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- `labels`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.