HomeMYSQLExplain the difference between CHAR and VARCHAR.

Explain the difference between CHAR and VARCHAR.

In MySQL, CHAR and VARCHAR are both used to store text/string data, but they behave differently in terms of storage, length, and performance. Here’s a detailed comparison:


1. Storage and Length

FeatureCHARVARCHAR
LengthFixed-lengthVariable-length
StorageAlways uses the full declared length. If you define CHAR(10) and store 'Hi', it still uses 10 bytes (padded with spaces).Only uses as much storage as needed for the string plus 1 or 2 bytes for length. 'Hi' in VARCHAR(10) uses 2 bytes + 2 bytes (for length) = 4 bytes.
Maximum Length0–2550–65535 (depending on row size and character set)

2. Padding

  • CHAR: Pads the remaining space with spaces to meet the fixed length.
CHAR(5): 'Hi' → stored as 'Hi   '
  • VARCHAR: Stores the exact string without extra spaces.

3. Performance

  • CHAR: Faster for fixed-length strings because MySQL knows the exact size of each row.
  • VARCHAR: Slightly slower for updates/reads in some cases because the length varies, and extra bytes are used to store the length.

4. Use Cases

  • CHAR: Best for fixed-length data like:
    • Country codes ('USA', 'IND')
    • Status codes ('Y', 'N')
  • VARCHAR: Best for variable-length data like:
    • Names
    • Email addresses
    • Descriptions

5. Trailing Spaces Behavior

  • CHAR: Trailing spaces are trimmed when retrieving data.
  • VARCHAR: Trailing spaces are kept as entered.

Summary:

  • CHAR → fixed-length, faster for short, consistent-sized strings.
  • VARCHAR → variable-length, saves space for strings of varying sizes.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *