Menu

MySQL CHAR: Fixed-Length Strings and Trailing Spaces

Updated on

MySQL CHAR(M) stores a fixed-length character string of up to M characters, where M ranges from 0 to 255. When a value is stored, MySQL pads it on the right with spaces to the declared width. When it is retrieved, trailing spaces are removed by default unless the PAD_CHAR_TO_FULL_LENGTH SQL mode is enabled. See MySQL’s CHAR and VARCHAR reference.

Syntax

CHAR[(M)]

If M is omitted, the length is 1. The length is measured in characters, while storage depends on the character set because a character can take multiple bytes.

Example: fixed-width code

Use CHAR when values are consistently the same character length, such as a two-letter country code:

CREATE TABLE locations (
    location_id INT PRIMARY KEY,
    country_code CHAR(2) NOT NULL
);

INSERT INTO locations (location_id, country_code)
VALUES (1, 'US'), (2, 'JP');

Avoid assuming CHAR is always faster than VARCHAR; choose it based on the value shape and retrieval behavior. For variable-length text, see VARCHAR. VARCHAR preserves trailing spaces when values are stored and retrieved; CHAR removes its padding spaces on retrieval by default.

Compare CHAR values with trailing spaces

The treatment of trailing spaces in comparisons depends on the column collation’s PAD SPACE or NO PAD attribute. Therefore, comparison behavior is not determined by storage padding alone. Check the collation when trailing spaces are significant to an application’s identifiers. See MySQL’s collation pad attributes.