Question presented to candidate: "When you design a table, how do you choose between CHAR, VARCHAR and TEXT for a string column? What does each one actually do with the value, and does the choice affect performance?"
What a strong answer should cover:
CHAR(n)is fixed length and blank-padded;VARCHAR(n)is variable length with a maximum;TEXTis variable length without a declared maximum- Padding semantics: trailing spaces in
CHARare insignificant in comparisons and dropped when converted to text, which produces surprises withLIKEand concatenation - Length limits are counted in characters in PostgreSQL and MySQL but in bytes in SQL Server; too-long values raise an error, while an explicit cast truncates
- Engine facts: in PostgreSQL there is no performance difference and
TEXTorVARCHARis recommended; SQLite ignores declared lengths entirely (type affinity); MySQLTEXTneeds a prefix length to be indexed; SQL ServerTEXTis deprecated in favour ofVARCHAR(MAX) - A sensible rule: use
TEXT/VARCHARby default, a length or CHECK only when it is a real business rule,CHARalmost never
Code / implementation expected: Optional — show what each type stores for 'ab' and how comparisons with trailing spaces behave.
Schema used by the examples: