Database.Beginner.What is the difference between CHAR and VARCHAR?

Difference Between CHAR and VARCHAR in SQL

FeatureCHAR(n)VARCHAR(n)
MeaningFixed-length stringVariable-length string
StorageAlways exactly n charactersOnly stores the actual length used (up to n)
PaddingPads with spaces if shorter than nNo padding — stores only the actual characters
PerformanceSlightly faster for fixed-size valuesMore storage-efficient for variable sizes
Use CaseWhen all values are about the same lengthWhen values vary widely in length
ExampleCHAR(5) always stores 5 charactersVARCHAR(5) stores 1–5 characters

1. CHAR(n) — Fixed Length

  • Always exactly n characters.
  • If the input is shorter, it’s padded with spaces.
  • Faster for fixed-length data because the database knows exactly how much space each value takes.

Example:

CREATE TABLE ExampleChar (
    code CHAR(5)
);

Insert:

INSERT INTO ExampleChar (code) VALUES ('A1');
code
A1

Always takes 5 bytes (assuming 1 byte per character, like in ASCII).

2. VARCHAR(n) — Variable Length

  • Stores only the characters you provide (up to n).
  • No extra spaces.
  • More storage efficient when lengths vary a lot.

Example:

CREATE TABLE ExampleVarchar (
    code VARCHAR(5)
);

Insert:

INSERT INTO ExampleVarchar (code) VALUES ('A1');
code
A1

Takes only 2 bytes for A1, plus 1–2 bytes extra to store the length internally (depends on DB engine).

When Should You Use CHAR vs VARCHAR?

Use CHAR WhenUse VARCHAR When
Data is always fixed lengthData is variable length
Example: country codes (US, FR)Example: names, emails, descriptions
Speed is a tiny bit more importantStorage efficiency is important
Minor gain for huge tablesBetter if length varies a lot

Real-World Example

FieldTypeWhy
Country codeCHAR(2)Always 2 characters — US, FR, JP.
User emailVARCHAR(255)Varies a lot — from short to very long addresses.
Phone numberCHAR(10)Always 10 digits (in some countries).
AddressVARCHAR(500)Highly variable.

In Short

CHAR(n): Fixed-length string — always n characters, padded with spaces.
VARCHAR(n): Variable-length string — stores exactly what you insert, no padding.

This entry was posted in Без рубрики. Bookmark the permalink.