
CHAR and VARCHAR
Definition:
Both CHAR and VARCHAR are string data types used to store text in MySQL.
However, they differ in how they store and manage the length of the string.
Key Differences:
CHAR and VARCHAR
Feature | CHAR | VARCHAR |
---|---|---|
Length Type | Fixed-length | Variable-length |
Storage | Always uses the defined number of characters (pads with spaces if shorter) | Uses only as much space as the actual data (plus 1 or 2 bytes for length info) |
Padding | Pads spaces to fill the fixed length | No padding applied |
Speed | Slightly faster for fixed-size data (like codes, IDs) | Slightly slower due to variable storage management |
Syntax Example | CHAR(10) | VARCHAR(10) |
Best Use Case | Fixed-length data (e.g., country codes, gender, etc.) | Variable-length data (e.g., names, addresses) |
SQL Example:
CREATE TABLE example (
id INT,
name_char CHAR(10),
name_varchar VARCHAR(10)
);
INSERT INTO example VALUES (1, 'John', 'John');
SELECT
CONCAT("'", name_char, "'") AS char_output,
CONCAT("'", name_varchar, "'") AS varchar_output
FROM example;
Output:
char_output | varchar_output |
---|---|
'John ' | 'John' |
Explanation:
CHAR(10)
→ always reserves 10 characters, padding extra spaces for shorter values.VARCHAR(10)
→ stores only 4 characters for'John'
, saving storage space.
In short:
🧠 Use CHAR for fixed-length data (constant size) and VARCHAR for variable-length text (flexible size).