Junior — Middle
What is the difference between CHAR and VARCHAR data types in SQL, and in which cases is each better to use?
sobes.tech AI
Answer from AI
In SQL, the data types CHAR and VARCHAR differ in how they store data and use memory:
-
CHAR(n) — fixed-length string. If the string is shorter than n, the remaining space is filled with spaces. Used when data length is always the same, such as country codes, statuses.
-
VARCHAR(n) — variable-length string up to n characters. Stores only the actual characters plus a small overhead byte for length. Better suited for data with variable length, such as names, addresses.
Usage:
- CHAR is efficient for fixed-length data as it is faster to process and easier to index.
- VARCHAR saves space for variable-length data but may have slight overhead.
Example:
CREATE TABLE users (
country_code CHAR(2), -- always 2 characters
username VARCHAR(50) -- up to 50 characters
);