
They are both used to store text (like names, addresses, etc.) in a MySQL database.
But they work differently:
Feature | CHAR | VARCHAR |
---|---|---|
Storage | Fixed size | Variable size |
Example | Always takes same space | Takes only as much as needed |
CHAR(10) vs. VARCHAR(10)
- CHAR(10): Like a rigid box that’s always 10 cm wide, no matter what’s inside.
- Example: Storing ‘Tom’ in CHAR(10)
- Stored as: ‘Tom ‘ (3 letters + 7 spaces to fill the 10-character length)
- Visual: [Tom_______] (fixed 10-character box)
- VARCHAR(10): Like a flexible box that adjusts to the item’s size, up to a maximum of 10 cm.
- Example: Storing ‘Tom’ in VARCHAR(10)
- Stored as: ‘Tom’ (just the 3 letters, no extra spaces)
- Visual: [Tom] (box shrinks to fit content, max 10 characters)
✅ Difference Between CHAR
and VARCHAR
in MySQL
Feature | CHAR | VARCHAR |
---|---|---|
Length Type | Fixed-length | Variable-length |
Storage | Always uses the specified length | Uses only as much as needed + 1 or 2 bytes overhead |
Trailing Spaces | Removed when stored | Preserved when stored |
Performance | Faster for fixed-length values | Slightly slower due to variable size |
-- Create a table with CHAR and VARCHAR columns
CREATE TABLE name_example (
char_name CHAR(10),
varchar_name VARCHAR(10)
);
-- Insert data
INSERT INTO name_example (char_name, varchar_name) VALUES ('Tom', 'Tom');
-- Select data to show the difference
SELECT char_name, LENGTH(char_name) AS char_length,
varchar_name, LENGTH(varchar_name) AS varchar_length
FROM name_example;