Australian cloud for business software — built and run in Sydney since 2002

NetLeverage
NetLeverage

MySQL ERROR 1366 (HY000) Incorrect string value: how to store 4-byte characters with utf8mb4

Technical article
Troubleshooting

About this article: This article is reviewed against the cited sources. This is source research, not lab validation. Check the stated versions and your own requirements before making changes.

When an INSERT or UPDATE stops with ERROR 1366 (HY000): Incorrect string value: '...' for column 'note' at row 1, MySQL has met a character that the column's character set cannot hold. A typical case, in our own reading, is a four-byte character such as an emoji sent to a utf8mb3 column, because utf8mb3 holds only the Basic Multilingual Plane. Check the column's character set and the connection's, save the table, then convert the column to utf8mb4.

What the error means

The MySQL 8.4 Error Reference lists number 1366, SQLSTATE HY000, symbol ER_TRUNCATED_WRONG_VALUE_FOR_FIELD, with the text "Incorrect %s value: '%s' for column '%s' at row %ld". The first value is the kind of value. In the 8.4.0 source, sql/field.cc fills it with the word decimal, integer or string. This fault is the string form. The numeric forms share the number but have other causes.

Our own reading of Field_longstr::check_string_copy_error in 8.4.0: for a string, the server finds the first position in the incoming bytes that is not well formed or cannot be converted to the column's character set, prints the bytes from there in a printable form, and raises this message as a warning. Read the printed bytes as the first character the column rejected.

What happens next depends on the SQL mode. The Server SQL Modes page says "If strict mode is not in effect, MySQL inserts adjusted values for invalid or missing values and produces warnings". With strict mode, an INSERT or UPDATE that hits an invalid value is an error and, for transactional tables, the statement is rolled back. The default mode list for MySQL 8.4 includes STRICT_TRANS_TABLES. In a session without strict mode the row is stored with an adjusted value and only SHOW WARNINGS records the fault.

The character sets differ as follows. The 3-byte and 4-byte conversion page says "utf8mb3 supports only characters in the Basic Multilingual Plane (BMP). utf8mb4 additionally supports supplementary characters that lie outside the BMP." It also says utf8mb3 uses a maximum of three bytes per character and utf8mb4 a maximum of four. In MySQL 8.4 utf8 is a deprecated alias for utf8mb3, and SHOW statements and INFORMATION_SCHEMA display utf8mb3. The manual's recommendation is "The recommended character set for MySQL is utf8mb4."

Likely causes

Cause What you see How to confirm
The column or table is utf8mb3 (or utf8) Only characters outside the BMP fail, such as emoji SHOW CREATE TABLE shows utf8mb3 for the column
The column uses a single-byte set such as latin1 Characters outside that set are rejected or altered (our own reading) SHOW CREATE TABLE shows latin1
The connection character set cannot carry the character The column is utf8mb4, yet characters are still rejected or altered (our own reading) SHOW SESSION VARIABLES LIKE 'character\_set\_%'; shows utf8mb3 or another set
The bytes are not valid text in the column's set Data came from a file or program in a different encoding The source's encoding differs from the column's; the column character set conversion page says a column's contents "should be encoded in the column character set"
The mode is not strict No error, a warning, and an adjusted value SHOW WARNINGS after the statement; SELECT @@SESSION.sql_mode; has no strict mode

Prove the cause before changing anything

All of these only read.

  1. Name the column in the message, and the row number. The row number is the position in a multi-row statement.
  2. Read the definition and character set of the column:
SHOW CREATE TABLE app.tickets\G
  1. Read the same from the Information Schema. The manual says the names utf8 and utf8_... are displayed as utf8mb3 and utf8mb3_...; utf8mb4 is shown as utf8mb4 (our own reading):
SELECT COLUMN_NAME, CHARACTER_SET_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = 'app' AND TABLE_NAME = 'tickets';
  1. Read the connection's character sets. character_set_client is what the client sends, and the server converts it to character_set_connection:
SHOW SESSION VARIABLES LIKE 'character\_set\_%';
  1. Read the SQL mode, which tells you whether the same fault would be silent:
SELECT @@SESSION.sql_mode;

Fix

Check the connection first: the 3-byte and 4-byte conversion page says "applications that expect to send 4-byte characters must ensure that the server understands them". Then convert the column.

Set the connection character set to utf8mb4

First save the current state: run these two statements and copy both results into charset-before.txt.

SHOW SESSION VARIABLES LIKE 'character\_set\_%';
SHOW SESSION VARIABLES LIKE 'collation\_%';

Risk: the next statement changes the character set of the current connection only. Applications that expect at most three bytes per character may then receive four-byte characters; the 3-byte and 4-byte conversion page warns that "applications that expect to receive a maximum of three bytes per character may have problems".

Set it:

SET NAMES 'utf8mb4';

The connection page says this equals setting character_set_client, character_set_results and character_set_connection to the same set, and that setting character_set_connection also implicitly sets collation_connection to the default collation for that set.

This changes only the session that runs it. An application sets its own connection character set when it connects, through its driver or client option; the connection page describes the default-character-set option for client programs.

To undo it: set those variables back to the values saved in charset-before.txt, then run the two SHOW SESSION VARIABLES statements again.

Risk: if you need to back out, the next statements change the character set and collation of the current connection back to the saved values. Characters outside the restored set sent on this connection are rejected or altered again.

SET character_set_client = <saved value>;
SET character_set_results = <saved value>;
SET character_set_connection = <saved value>;
SET collation_connection = <saved value>;

Convert the column to utf8mb4

The 3-byte and 4-byte conversion page shows a table converted with ALTER TABLE ... MODIFY col CHAR(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL. A column converted this way must keep its attributes: the column character set conversion page says "If you specified attributes when creating a column initially, you should also specify them when altering the table with ALTER TABLE."

First save the current state:

mysqldump --single-transaction --result-file=tickets-before.sql app tickets

Also save the output of SHOW CREATE TABLE app.tickets\G from step 2 in tickets-create-before.txt.

Risk: the next statement rebuilds the table app.tickets and changes the character set of note. The column character set conversion page says ALTER TABLE statements that change character sets or collations "must be performed using ALGORITHM=COPY". The new column can hold more bytes per character, so indexes on it may exceed the key limit; see MySQL ERROR 1071 (42000): Specified key was too long; max key length is 767 bytes (or 3072): count the bytes, then use a DYNAMIC table or a shorter index. With foreign keys, the ALTER TABLE page says that while foreign_key_checks is enabled, character set conversion "is not permitted on tables that include a character string column used in a foreign key constraint". The same page names disabling foreign_key_checks before the conversion as the workaround; that is a separate changing step that these steps do not cover.

Convert only the column that failed, repeating its other attributes from the saved definition:

ALTER TABLE app.tickets MODIFY note VARCHAR(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL;

Use MODIFY rather than CONVERT TO CHARACTER SET: the ALTER TABLE page says "To avoid data type changes of the type just described, do not use CONVERT TO CHARACTER SET. Instead, use MODIFY to change individual columns." That page explains that CONVERT TO can change TEXT to MEDIUMTEXT and VARCHAR to MEDIUMTEXT.

To undo it: run only the one that applies. Converting back to utf8mb3 fails or loses data once the table holds a four-byte character. If the table holds none, convert the column back to the definition in tickets-create-before.txt; the statement below shows the definition of the example column.

Risk: if you need to back out, the next statement converts note back to utf8mb3. It fails, or turns characters outside the Basic Multilingual Plane into errors or replacement characters, if the table already holds any.

ALTER TABLE app.tickets MODIFY note VARCHAR(500) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL;

If the table already holds a four-byte character, load the dump instead.

Risk: if you need to back out this way, the next command runs the dump tickets-before.sql, which holds DROP TABLE before CREATE TABLE (the default --opt set), so it drops app.tickets and creates it again. Every row inserted or changed since the dump is lost, and a reload cannot be undone.

mysql app < tickets-before.sql

Then read the definition again with SHOW CREATE TABLE app.tickets\G.

Example (illustrative): On db01, app.tickets.note is VARCHAR(500) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL. A customer pastes a message containing U+1F600, which UTF-8 encodes in four bytes. The insert fails with ERROR 1366 (HY000): Incorrect string value: '\xF0\x9F\x98\x80' for column 'note' at row 1. SHOW CREATE TABLE shows utf8mb3 and the connection reports utf8mb4, so the column is the cause. After the MODIFY, the column holds up to 500 x 4 = 2,000 bytes instead of 500 x 3 = 1,500, and the insert succeeds.

Confirm the fix

  1. SHOW CREATE TABLE app.tickets\G shows utf8mb4 and the intended collation for note.
  2. The statement that failed now runs, and a SELECT returns the same character.
  3. SHOW WARNINGS after the insert is empty.

What to watch afterwards

  • Make new tables utf8mb4. The manual says the default server character set is utf8mb4 and warns that utf8mb3 is deprecated and expected to be removed in a future major release.
  • The 3-byte and 4-byte conversion page says "One tradeoff is that this may increase data storage space requirements."
  • Convert the other character columns of the same table, or a later insert fails on the next column.
  • Check replicas: the 3-byte and 4-byte conversion page says "if character sets that support supplementary characters are to be used on the source, all replicas must understand them as well."

Risks and limits

  • These commands have not been run or lab-tested.
  • The column character set conversion page says "Conversion may be lossy if the column contains characters that are not in both character sets." The 3-byte and 4-byte conversion page says that in terms of table content, conversion from utf8mb3 to utf8mb4 "presents no problems"; a conversion from another set may lose characters.
  • If stored values are encoded in a different character set from the column's, the manual describes converting through a binary type first. No steps for it are given here.
  • The printed form of the offending bytes is our own reading of the source, not a documented format.
  • The message text and code path are from MySQL 8.4.0; other releases may differ.

Sources