CHAR vs VARCHAR vs TEXT
CHAR vs VARCHAR vs TEXT
Choosing the correct string data type impacts disk utilization, memory cache efficiency, and validation semantics.
Comparison Table
| Data Type | Length Behavior | Storage Overhead | Ideal Use Case |
|---|---|---|---|
| CHAR(n) | Fixed (space-padded) | Exact n bytes | Country codes (US, CA), UUID, hashes |
| VARCHAR(n) | Variable (up to n) | Length + 1-2 bytes | Names, emails, URLs, titles |
| TEXT | Variable (unlimited) | Length + 1-4 bytes | Articles, comments, logs, raw content |
Detailed Breakdown
- CHAR(n): Fixed-length character storage. If the string is shorter than
n, the database pads it with trailing spaces. When retrieved, trailing spaces are often stripped. - VARCHAR(n): Stores only the characters you insert, plus a small prefix indicating string length (1 byte for strings < 255 characters, 2 bytes otherwise).
- TEXT: Used when text size cannot be known beforehand. In PostgreSQL,
VARCHARandTEXTuse the same underlying storage engine (TOAST), resulting in virtually identical performance. In MySQL, largeTEXTcolumns may be stored out-of-row on disk.
Best Practice Guidelines
- Use CHAR(n) only when strings are strictly uniform in size (e.g. state abbreviations, SHA-256 hashes).
- Use VARCHAR(n) to enforce business logic limits at the database level (e.g.
VARCHAR(255)for email addresses). - Use TEXT for free-form descriptions, notes, and arbitrary text bodies.