Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Postgres: value too long for type character varying(255)

22001 means the string exceeds the column limit and Postgres truncates nothing. Widen with care, validate at the edge, and know rewrite and lock costs.

~5 min readSQL
#postgresql#sql#varchar#migrations
Bold white headline reading VALUE TOO LONG with a Postgres column crate rejecting an amber overflow block.

Introduction & Quick Summary

Postgres rejects the write instead of cutting the string:

code
ERROR: value too long for type character varying(50) SQL state: 22001

The target column is varchar(50) and the value is longer than fifty characters. Postgres truncates nothing on an assignment: an INSERT or UPDATE that exceeds the declared length fails, the statement rolls back, and the connection stays usable. 22001 is the SQLSTATE for string data right truncation, which is the standard's name for this limit.

Where it appears:

  • INSERT with a name, slug, or URL longer than the column allows.
  • UPDATE that sets a value from a concat or format result.
  • COPY FROM of a CSV whose column widths grew.
  • A cast in a view that narrows a text column to varchar(n).
  • A migration that resized a column down while old data was longer.
  • Multibyte text where the character count fits but the byte count does not matter, or the reverse.

Quick answer: find the column, decide whether the limit or the data is wrong, and widen the column. Widening is a metadata change in modern Postgres; narrowing rewrites the table.

Core Mechanics, Signatures & Reproducible Setup

varchar(n) enforces a maximum length in characters, not bytes. The check runs when a value is assigned to the column, including through a DEFAULT expression, a trigger assignment, or a COPY. An explicit cast to varchar(n) behaves differently: it truncates.

-- repro CREATE TABLE accounts ( id bigserial PRIMARY KEY, handle varchar(12) NOT NULL, bio varchar(140) ); INSERT INTO accounts (handle) VALUES ('this_handle_is_too_long'); -- ERROR: value too long for type character varying(12)
-- explicit cast: no error, silent truncation SELECT 'this_handle_is_too_long'::varchar(12) AS truncated; -- this_handle

That asymmetry is the source of most surprises. Application code that casts to make an error go away loses data without any log line.

-- character length versus byte length SELECT length('한국어'), octet_length('한국어'); -- 3 9

A three-character string that fits varchar(3) occupies nine bytes on disk. Byte limits appear in index entries (about 2704 bytes for a btree row) and in varchar lengths only through the character count.

The error family around it:

SQLSTATEMessageMeaning
22001value too long for type character varying(n)string exceeds the column limit
22003numeric value out of rangeinteger or numeric overflow
22007invalid input syntax for type timestampunparseable date input
22P02invalid input syntax for type integernon-numeric text where a number is required
23502null value in column violates not-nullmissing required value
23514new row violates check constrainta value rule failed

Key Comparison Table

FixStatementRewrites tableUse when
Widen varchar(n)ALTER COLUMN TYPE varchar(255)no, metadata onlythe limit was too small
Switch to textALTER COLUMN TYPE textnono business limit exists
Add a check constraintADD CONSTRAINT ... CHECK (length(x) <= n)nokeep a rule without a type limit
Truncate at the boundaryleft(value, 50) in the insertn/athe extra characters are noise
Reduce the value at the sourcevalidation in the appn/athe data is wrong, not the column
Narrow the columnALTER COLUMN TYPE varchar(20)yescleaning up an oversized column

Behaviour by type:

TypeStoresPadsEnforces length
varchar(n)variable, up to n charactersnoyes
varcharvariable, unlimitednono
textvariable, unlimitednono
char(n)fixed n charactersyes, with spacesyes

varchar and text have identical storage and performance in Postgres; the length limit is a constraint, not a storage format.

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Identify the column from the error

The message names the type, not the column, so a wide INSERT can be ambiguous. Ask the catalogue.

SELECT table_schema, table_name, column_name, data_type, character_maximum_length FROM information_schema.columns WHERE data_type IN ('character varying', 'character') AND character_maximum_length IS NOT NULL AND table_name = 'accounts' ORDER BY ordinal_position;
sql
-- what the table actually uses, including constraints added later \d+ accounts

The SQL schema tool renders the same information from a pg_dump --schema-only file, which is faster when you are reading a production schema you cannot connect to.

2. Widen without locking the table for long

Increasing a varchar length or switching to text changes only the catalogue, so it takes an ACCESS EXCLUSIVE lock briefly but does not rewrite rows. That lock still waits behind long queries, so set a lock timeout.

BEGIN; SET LOCAL lock_timeout = '3s'; ALTER TABLE accounts ALTER COLUMN handle TYPE varchar(64); COMMIT;
-- verify the new limit and that no rewrite is pending SELECT attname, atttypmod FROM pg_attribute WHERE attrelid = 'accounts'::regclass AND attname = 'handle';

If the ALTER times out, retry later or use a migration tool that sets the same lock_timeout and retries automatically. Do not increase the timeout to minutes on a busy table; the lock queue blocks every writer behind it.

3. Never cast to silence the error

An explicit cast truncates, and the truncation happens where nobody looks.

-- silent data loss INSERT INTO accounts (handle) VALUES ('a_very_long_handle'::varchar(12)); -- visible and reversible INSERT INTO accounts (handle) VALUES (left('a_very_long_handle', 12));

Use left() or substring() when truncation is intended, and add a check constraint or application validation when it is not. Keep the cast out of generated views as well: a view that casts to varchar(20) hides the loss from every query that reads it.

4. Handle multibyte and byte limits correctly

Character and byte limits are different checks, and both appear in this error class.

CREATE TABLE notes (body varchar(10)); INSERT INTO notes VALUES (repeat('한', 11)); -- ERROR: value too long for type character varying(10) -- check before inserting, in the same unit the column uses SELECT length(repeat('한', 10)) AS chars, octet_length(repeat('한', 10)) AS bytes; -- 10 30

For columns that must fit an external byte limit, such as a 64-byte header, enforce it with a check on octet_length and store as text:

ALTER TABLE notes ADD CONSTRAINT notes_body_bytes CHECK (octet_length(body) <= 64);

5. Validate at the boundary and keep the database honest

The database should reject bad data; the application should avoid sending it. Both layers have a job, and the error should be rare rather than routine.

sql
CREATE OR REPLACE FUNCTION normalize_handle(input text) RETURNS varchar(64) AS $$ DECLARE cleaned text := lower(regexp_replace(input, '[^a-z0-9_]+', '_', 'g')); BEGIN IF cleaned = '' THEN RAISE EXCEPTION 'handle is empty after normalization' USING ERRCODE = '22023'; END IF; IF length(cleaned) > 64 THEN RAISE EXCEPTION 'handle exceeds 64 characters' USING ERRCODE = '22001'; END IF; RETURN cleaned::varchar(64); END; $$ LANGUAGE plpgsql IMMUTABLE;

Raising with the same SQLSTATE the client already handles keeps the error path consistent, and the message names the rule instead of the column type. Test the function with the SQL scratchpad against a copy of the schema before shipping it.

Common Compilation/Runtime Mistakes & Version Gotchas

Believing text is slower than varchar(n). They use the same storage and the same functions. The length limit is a constraint; choosing varchar(255) for performance is a habit from other databases.

Narrowing a column without checking the data. ALTER COLUMN TYPE varchar(20) fails on existing longer rows, and with USING left(col, 20) it succeeds while destroying data. Count the rows first: SELECT count(*) FROM t WHERE length(col) > 20.

Forgetting that char(n) pads. A char(10) value compares equal to a shorter literal after trailing spaces are stripped, and length() reports the padded length. Use varchar or text unless the fixed width is part of the format.

Trusting a client-side truncation. An ORM that truncates silently in one language version and raises in another makes this error appear after an upgrade. Check the model definition, and let the database be the last line of defence rather than the first.

Dockerized copies with different schemas. A staging database migrated but production not, or the reverse, produces 22001 only in one environment. Compare schemas with pg_dump --schema-only on both, and diff the files before debugging the code.

Version differences worth knowing. Since PostgreSQL 9.2, increasing the length of a varchar column is a metadata-only change; before that it rewrote the table. PostgreSQL 11 added the ability to add a column with a non-null default without a rewrite, which changed how backfills are written. ALTER TABLE ... ADD CONSTRAINT ... NOT VALID followed by VALIDATE CONSTRAINT has been the standard way to add a check to a large table since 9.1, and it is still the right pattern for length rules.

Verification. After the change, insert a value at the new limit and one over it, and confirm the second still fails with 22001. A widened column should not silently accept unlimited data; if that is the intent, use text and say so in the migration.

Reference material: Character types and Appendix A. PostgreSQL error codes.

Official references

primary documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.