VARCHAR vs CHAR in MySQL: Key Differences and Usage
CHAR is a fixed-length string type that always uses the same amount of storage, while VARCHAR is a variable-length string type that uses only as much storage as needed plus one or two bytes for length. CHAR is faster for fixed-size data, and VARCHAR is more space-efficient for variable-size data.Quick Comparison
Here is a quick side-by-side comparison of CHAR and VARCHAR in MySQL.
| Factor | CHAR | VARCHAR |
|---|---|---|
| Storage Size | Fixed length, always uses declared size | Variable length, uses actual string length + 1 or 2 bytes |
| Maximum Length | 0 to 255 characters | 0 to 65,535 bytes (depending on row size and character set) |
| Padding | Right-padded with spaces to fixed length | No padding, stores exact string length |
| Performance | Faster for fixed-length data due to fixed storage | Slightly slower due to variable length handling |
| Use Case | Best for fixed-size data like codes or IDs | Best for variable-size data like names or emails |
Key Differences
CHAR stores strings with a fixed length. If the string is shorter than the declared size, MySQL pads it with spaces on the right to fill the length. This makes CHAR fast for fixed-size data because the storage size is predictable.
VARCHAR stores strings with variable length. It uses only the space needed for the string plus one or two extra bytes to record the length. This saves space when string lengths vary a lot but adds a small overhead for length management.
Another difference is the maximum size: CHAR can hold up to 255 characters, while VARCHAR can hold much longer strings, limited by the row size and character set. Also, CHAR pads with spaces, which can affect comparisons, while VARCHAR stores strings exactly as given.
CHAR Example
CREATE TABLE example_char ( code CHAR(5) ); INSERT INTO example_char (code) VALUES ('abc'); SELECT code, LENGTH(code) AS length, OCTET_LENGTH(code) AS byte_length FROM example_char;
VARCHAR Equivalent
CREATE TABLE example_varchar ( code VARCHAR(5) ); INSERT INTO example_varchar (code) VALUES ('abc'); SELECT code, LENGTH(code) AS length, OCTET_LENGTH(code) AS byte_length FROM example_varchar;
When to Use Which
Choose CHAR when you know the data will always be the same length, like fixed codes, country abbreviations, or status flags. This gives you faster access and simpler storage.
Choose VARCHAR when the data length varies, such as names, emails, or descriptions. It saves space and handles different lengths efficiently.
In general, prefer VARCHAR for most text data unless you have a clear reason to use fixed-length CHAR.
Key Takeaways
CHAR uses fixed storage and pads strings with spaces.VARCHAR uses variable storage and stores exact string length.CHAR is faster for fixed-length data; VARCHAR is more space-efficient for variable-length data.CHAR for fixed-size codes and VARCHAR for variable-size text.CHAR is 255, while VARCHAR can be much longer.