What is the difference between CHAR and VARCHAR?
Both store strings, but they differ in storage and padding.
CHAR(n) — fixed-length. Always uses
nbytes (or characters); shorter values are padded with spaces. Faster for fixed-size data.
VARCHAR(n) — variable-length. Stores only the actual string plus a 1- or 2-byte length prefix. Saves space when lengths vary.
Use CHAR for codes of consistent length (country codes, gender flags); use VARCHAR for everything else — names, emails, descriptions.
-- CHAR: fixed-length, padded
CREATE TABLE countries (
code CHAR(2) NOT NULL, -- Always 2 chars: 'US', 'UK'
name VARCHAR(100) NOT NULL -- Variable: 'United States', 'UK'
);
-- Storage comparison
-- CHAR(10) storing 'hi' → 10 bytes (padded with spaces)
-- VARCHAR(10) storing 'hi' → 3 bytes (2 chars + 1 length byte)
-- CHAR strips trailing spaces on retrieval
INSERT INTO test (char_col) VALUES ('hi ');
SELECT CHAR_LENGTH(char_col) FROM test; -- 2 (spaces stripped!)
-- VARCHAR preserves trailing spaces
INSERT INTO test (varchar_col) VALUES ('hi ');
SELECT CHAR_LENGTH(varchar_col) FROM test; -- 5 (spaces kept)CHAR(2) always stores 2 bytes — perfect for country codes. VARCHAR(100) uses only the actual length + 1 byte.
CHAR strips trailing spaces on retrieval; VARCHAR preserves them. CHAR is faster for truly fixed-length data because the database knows the exact offset.
CHAR = fixed length (padded), VARCHAR = variable length (efficient). CHAR strips trailing spaces. Use CHAR for fixed codes (2-char country codes, 36-char UUIDs).
Use VARCHAR for everything else. This is one of the most asked data type questions.