Senior
What is the difference between the TEXT data type and VARCHAR in PostgreSQL, and how does VARCHAR differ from CHAR?
sobes.tech AI
Answer from AI
In PostgreSQL, the TEXT and VARCHAR types are very similar and often interchangeable, but there are some differences:
- TEXT is an unlimited length string.
- VARCHAR(n) is a string with a length limit of n characters.
If the string length exceeds n, using VARCHAR(n) will result in an error, whereas TEXT is unlimited.
Differences between VARCHAR and CHAR:
- CHAR(n) is a fixed-length string of length n. If the string is shorter, it is padded with spaces on the right.
- VARCHAR(n) is a variable-length string with a maximum length of n.
Example:
CREATE TABLE example (
col_text TEXT,
col_varchar VARCHAR(50),
col_char CHAR(10)
);
INSERT INTO example VALUES ('hello', 'hello', 'hello');
-- col_char will store 'hello ' with spaces up to length 10
Overall, TEXT and VARCHAR(n) have almost no performance difference, and CHAR is rarely used when a fixed length is needed.