✏️ Explanatory Question
Level: Basic — A favourite question to check if you understand fixed vs variable length storage.
Both CHAR and VARCHAR store character (string) data, but they differ in how they allocate storage.
CHAR is a fixed-length type. If you define CHAR(10) and store the word "cat", MySQL still uses all 10 characters, padding the rest with spaces. It is faster for data that is always the same length.
VARCHAR is a variable-length type. VARCHAR(10) storing "cat" uses only 3 characters plus 1–2 bytes to record the length. It saves space for data of varying length.
| CHAR | VARCHAR |
|---|---|
| Fixed-length storage. | Variable-length storage. |
| Length range: 0 to 255 characters. | Length range: 0 to 65,535 characters. |
| Pads with trailing spaces to fill the size. | Stores only actual characters + 1–2 length bytes. |
| Slightly faster for fixed-size data. | More space-efficient for varying data. |
| Wastes space if values vary a lot. | Small overhead per value for the length prefix. |
| Best for: codes, flags, fixed IDs. | Best for: names, emails, descriptions. |
Storing the value "cat" in each type:
"cat " (padded)"cat" onlyCREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
country_code CHAR(2), -- always 2 chars: 'IN', 'US'
full_name VARCHAR(100), -- varies in length
gender CHAR(1) -- 'M', 'F', 'O'
);
INSERT INTO users (country_code, full_name, gender)
VALUES ('IN', 'Rumman Ansari', 'M');