Explain the difference between 'CHAR' and 'VARCHAR' data types.

Instruction: Describe these two data types and the scenarios in which each is preferable.

Context: This question tests the candidate's understanding of SQL data types and their practical application in database design.

Updated

Official answer

CHAR(n) is a fixed-length, blank-padded character type; VARCHAR(n) accepts variable-length strings up to a limit. Exact storage and comparison behavior depend on the database and encoding. Do not assume one character equals one byte or that VARCHAR always has two bytes of overhead.

In PostgreSQL, this illustrates blank-padding semantics:

SELECT CAST('ab' AS char(4)) = CAST('ab  ' AS char(4)) AS char_equal,
       CAST('ab' AS varchar(4)) = CAST('ab  ' AS varchar(4)) AS varchar_equal;

The results are true and false respectively. Trailing spaces are treated differently in these comparisons. PostgreSQL does not give CHAR a general performance advantage over VARCHAR or text; blank padding can add cost.

Use a length limit when it expresses a genuine rule. A two-letter code can also be represented with text plus suitable validation; CHAR alone does not validate the allowed code set. Choose the type for semantics and verified database behavior, rather than a fixed-length-is-faster rule.

Related Questions