✏️ Explanatory Question

What is the difference between CHAR and VARCHAR?

👁 8 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

6

What is the difference between CHAR and VARCHAR?

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.

Rule of thumb: Use CHAR for fixed-size values (country codes, gender flags, MD5 hashes). Use VARCHAR for variable text (names, emails, addresses).

Side-by-Side Comparison

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.

Storage Illustration

Storing the value "cat" in each type:

CHAR(10)

  • Stores: "cat       " (padded)
  • Uses full 10 bytes
  • 7 bytes wasted as spaces

VARCHAR(10)

  • Stores: "cat" only
  • Uses 3 + 1 = 4 bytes
  • No wasted space

Quick Example

CREATE 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');
Interviewer tip: The one-liner they want — "CHAR is fixed-length and space-padded, best for fixed-size data; VARCHAR is variable-length and space-efficient, best for data that varies in length."