Video in progress

Which should you choose in PostgreSQL: `char(n)`, `varchar(n)` or `text`?

In PostgreSQL text and varchar are stored the same way internally and perform the same. varchar(n) only adds a length limit. char(n) pads the value with spaces and is almost never what you want.

📖 Answer

People coming from other databases often think "varchar(255) is faster". Not in PostgreSQL: all three are stored in the same varlena format.

SELECT 'ab'::char(5) = 'ab   '::char(5);   -- true, trailing spaces are ignored
SELECT length('ab'::char(5));             -- 2, but 5 characters on disk

char(n) causes odd bugs: "ab " arrives in Java and equals stops working.

Here is what I usually do:

  • text for ordinary strings;
  • if there is a real business limit (say, an ISO currency code is 3 characters), varchar(3) or text + CHECK (length(code) = 3).

The CHECK option is more convenient: changing the limit later is just swapping the constraint. Increasing the length of a varchar(n) doesn't rewrite the table in current versions either, but shrinking it does.

In JPA, @Column(length = 100) gives varchar(100) in schema generation; if you write the schema yourself with Flyway, it's your choice.