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.

Introduction & Quick Summary
Postgres rejects the write instead of cutting the string:
ERROR: value too long for type character varying(50)
SQL state: 22001The 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:
INSERTwith a name, slug, or URL longer than the column allows.UPDATEthat sets a value from aconcatorformatresult.COPY FROMof a CSV whose column widths grew.- A cast in a view that narrows a
textcolumn tovarchar(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_handleThat 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 9A 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:
| SQLSTATE | Message | Meaning |
|---|---|---|
| 22001 | value too long for type character varying(n) | string exceeds the column limit |
| 22003 | numeric value out of range | integer or numeric overflow |
| 22007 | invalid input syntax for type timestamp | unparseable date input |
| 22P02 | invalid input syntax for type integer | non-numeric text where a number is required |
| 23502 | null value in column violates not-null | missing required value |
| 23514 | new row violates check constraint | a value rule failed |
Key Comparison Table
| Fix | Statement | Rewrites table | Use when |
|---|---|---|---|
Widen varchar(n) | ALTER COLUMN TYPE varchar(255) | no, metadata only | the limit was too small |
Switch to text | ALTER COLUMN TYPE text | no | no business limit exists |
| Add a check constraint | ADD CONSTRAINT ... CHECK (length(x) <= n) | no | keep a rule without a type limit |
| Truncate at the boundary | left(value, 50) in the insert | n/a | the extra characters are noise |
| Reduce the value at the source | validation in the app | n/a | the data is wrong, not the column |
| Narrow the column | ALTER COLUMN TYPE varchar(20) | yes | cleaning up an oversized column |
Behaviour by type:
| Type | Stores | Pads | Enforces length |
|---|---|---|---|
varchar(n) | variable, up to n characters | no | yes |
varchar | variable, unlimited | no | no |
text | variable, unlimited | no | no |
char(n) | fixed n characters | yes, with spaces | yes |
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;-- what the table actually uses, including constraints added later
\d+ accountsThe 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 30For 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.
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 documentationThe SQL documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related SQL guides
All SQL guidesSQLite: database is locked (SQLITE_BUSY) under concurrent writes
SQLite allows one writer. Set a busy timeout, switch to WAL, start write transactions as IMMEDIATE, and reduce to a single writer connection.
SQL Window Functions: ROW_NUMBER, RANK, DENSE_RANK, and LEAD/LAG Explained
How the four ranking and offset functions differ on ties, why the default RANGE frame makes running totals repeat, and how LAG builds gap-and-island.
Postgres: column does not exist (SQLSTATE 42703)
42703 means the identifier you wrote is not the one that exists. Check case folding, alias scope, search_path and migration drift.
PostgreSQL: canceling statement due to statement timeout
The statement was canceled by statement_timeout. Find whether the role, the pooler or the client set it, then scope a longer budget to that job.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.