Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

MySQL 1406: Data too long for column

Strict mode rejects values wider than the column. Count characters against VARCHAR length, check charset bytes, and widen the column or validate input.

~5 min readSQL
#mysql#error-1406#strict-mode#schema
MySQL column slot overflowing with a text block and a strict mode gate beside it

Introduction & Quick Summary

An insert that worked in development is rejected in production:

code
mysql> INSERT INTO articles (title, body) VALUES ('A very long title ...', 'body'); ERROR 1406 (22001): Data too long for column 'title' at row 1

Quick answer: the value is longer than the column allows, and the server is running in strict mode, which turns what used to be a silent truncation into an error.

SHOW CREATE TABLE articles\G -- title varchar(120) NOT NULL SELECT CHAR_LENGTH('A very long title ...') AS chars, LENGTH('A very long title ...') AS bytes;

VARCHAR(120) counts characters, not bytes, so a title of 140 characters is rejected whether it is ASCII or Korean. Two decisions follow: widen the column to the length the data actually needs, or validate and shorten at the application boundary before the insert. Changing sql_mode to make the error disappear is the one option that keeps the data loss and hides it.

This guide covers what the three numbers in VARCHAR(n) really mean, how strict mode changed the behaviour in MySQL 5.7, the difference between character and byte limits for utf8mb4 and TEXT, and the failure modes where the value that is too long was produced by the app, a bulk load, or a replication lag.

Core Mechanics, Signatures & Reproducible Setup

MySQL has measured VARCHAR in characters since 4.1. VARCHAR(255) holds 255 characters and stores them in a variable number of bytes depending on the character set: 1 byte per character for latin1, up to 3 for utf8mb3, up to 4 for utf8mb4.

CREATE TABLE demo ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(10) NOT NULL, note TEXT, payload JSON ) DEFAULT CHARSET = utf8mb4; INSERT INTO demo (name) VALUES ('abcdefghij'); -- 10 chars, ok INSERT INTO demo (name) VALUES ('abcdefghijk'); -- 1406, 11 chars INSERT INTO demo (name) VALUES ('한글한글한글한'); -- 1406, 7 chars but 21 bytes INSERT INTO demo (name) VALUES ('한글한글한글'); -- ok, 6 of 10 characters

The last two lines are the whole confusion: VARCHAR(10) accepted six Korean characters (18 bytes) and rejected seven (21 bytes) — not because of a byte cap on the column, but because both are 6 and 7 characters respectively against a 10-character limit.

SELECT CHAR_LENGTH('한글한글한글한') AS chars, LENGTH('한글한글한글한') AS bytes; -- chars 7, bytes 21

A reproducible strict-mode comparison:

SELECT @@sql_mode; -- STRICT_TRANS_TABLES,ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,... SET SESSION sql_mode = 'STRICT_TRANS_TABLES'; INSERT INTO demo (name) VALUES ('abcdefghijk'); -- ERROR 1406 SET SESSION sql_mode = ''; INSERT INTO demo (name) VALUES ('abcdefghijk'); -- Query OK, 1 warning SHOW WARNINGS; -- 1265: Data truncated for column 'name'

In non-strict mode the insert succeeds and the stored value is abcdefghij; the data is already lost by the time the query returns.

Key Comparison Table

TypeLimit measured inOverflow behaviour in strict mode
VARCHAR(n)characterserror 1406
CHAR(n)characters, right-paddederror 1406 or 1265 on padding
TEXTbytes (65,535)error 1406, or truncated with warning
MEDIUMTEXT / LONGTEXTbytes (16 MB / 4 GB)error only near the limit
VARBINARY(n)byteserror 1406
JSONbytes, 1 GB maxerror on invalid JSON
Indexed VARCHARcharacters plus a byte prefix limit1071 "key too long"
sql_modeInsert longer than the columnResult
STRICT_TRANS_TABLES (default)rejectederror 1406, no row
STRICT_ALL_TABLESrejected, also for MyISAMerror 1406
'' (non-strict)truncatedwarning 1265, row inserted
INSERT IGNOREtruncatedwarning, row inserted
LOAD DATA LOCAL INFILEtruncated to fitwarning, row inserted
SymptomReal causeFix
Only some rows failvalues at the boundaryvalidate length, widen or trim
Fails after a charset migrationutf8mb3 to utf8mb4 changes byte sizecheck CHAR_LENGTH not LENGTH
Fails only in one environmentstrict mode differsalign sql_mode across servers
Fails only on emoji4-byte characters in utf8mb3convert the column to utf8mb4
Error names a generated columnexpression produces a longer valuewiden the generated column or the source

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. Measure before choosing a width

Decide the column width from the data, not from a round number:

SELECT MAX(CHAR_LENGTH(title)) AS max_chars, MAX(LENGTH(title)) AS max_bytes FROM articles; ALTER TABLE articles MODIFY title VARCHAR(200) NOT NULL;

VARCHAR stores only what is used, so a wider column costs no extra space per row (only the length prefix stays 1 or 2 bytes). The real ceilings are the row size limit (65,535 bytes for the whole row) and the index prefix limit, not the declared width.

2. Emoji, flags and 4-byte characters

A column created as utf8 is utf8mb3 in MySQL and cannot store 4-byte characters at all — the insert fails with 1366 (Incorrect string value), which is a different error from 1406 but arrives in the same migration:

SHOW VARIABLES LIKE 'character_set_%'; ALTER TABLE articles CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

After the conversion, a VARCHAR(10) column still accepts 10 characters, but its maximum storage grows from 30 to 40 bytes. If the table is near the row-size limit, the conversion is where error 1118 ("Row size too large") appears instead.

3. Strict mode differs between servers

A staging server with sql_mode='' accepts a 300-character title; production with the default strict mode rejects it at the first user with a long title. Align the mode in configuration rather than per session, and check it as part of the environment comparison:

SELECT @@GLOBAL.sql_mode, @@SESSION.sql_mode;

Per-application sessions that set sql_mode='' on connect are the worst case: the error disappears from the app and reappears in a reporting job that uses a different user.

4. Bulk loads and silent truncation

LOAD DATA and INSERT IGNORE downgrade 1406 to a warning. A load that reports "1,204 rows affected" can contain truncated values:

LOAD DATA LOCAL INFILE 'articles.csv' INTO TABLE articles FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 LINES (title, body); SHOW WARNINGS LIMIT 20; SELECT COUNT(*) FROM articles WHERE CHAR_LENGTH(title) = 200; -- suspicious pile-up at the limit

Counting rows that sit exactly at the column width finds truncation after the fact.

5. Application-side validation and honest errors

The database limit is the last line of defence, not the user experience. Validate with the same unit the column uses — characters — and return a clear message:

python
MAX_TITLE = 200 def clean_title(raw: str) -> str: title = " ".join(raw.split()) if len(title) > MAX_TITLE: # Python counts code points, MySQL counts characters raise ValueError(f"title is {len(title)} characters, limit is {MAX_TITLE}") return title

For grapheme clusters (emoji with modifiers), code points and MySQL characters agree more often than bytes do, but a strict character count still splits a combined emoji; truncate on grapheme boundaries in the UI and store the result.

6. Replication and replicas in a different mode

With statement-based replication, the statement re-executes on the replica. If the replica runs a non-strict sql_mode while the primary is strict, the primary rejects the write and the replica would have truncated it — or the reverse, producing divergence that surfaces as 1406 in a failover drill:

sql
-- same on primary and replica SET GLOBAL sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION';

Check SHOW SLAVE STATUS / SHOW REPLICA STATUS for Last_Error after a mode mismatch, and keep sql_mode in the managed configuration so a new replica inherits it.

The SQL formatter helps align the INSERT and ALTER statements while comparing environments, and the SQL schema designer shows the column widths before a migration is written.

Common Compilation/Runtime Mistakes & Version Gotchas

  • Setting sql_mode='' to make inserts pass. It converts an error into silent data loss that is much harder to detect.
  • Counting bytes for VARCHAR. VARCHAR(n) is characters; LENGTH() returns bytes and misleads the check.
  • Assuming TEXT is unlimited. It is 65,535 bytes including the length prefix; MEDIUMTEXT or LONGTEXT is the next step.
  • Widening without checking indexes. A VARCHAR(1000) with a full index exceeds the key length and fails with 1071.
  • Trusting INSERT IGNORE. It downgrades 1406 to a warning for every row it touches.
  • Ignoring the client's charset. A connection with character_set_client=latin1 mangles multi-byte input before the column limit is even reached.
  • MySQL 8 collation differences. utf8mb4_0900_ai_ci compares accent-insensitively; a "duplicate" check that relied on binary comparison can now behave differently, though the length rules are unchanged.

Official documentation: MariaDB error code reference (1406) and SQL modes and strict mode.

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.