Postgres - Choosing between varchar(n) and text

Postgres
Varchar
Text

So the question is often asked: Should I use the varchar(n) or text data type when defining a new column in a table? This is especially important to those coming from the MySQL world.

In Postgres, the varchar(n) and text data types both use the same underlying C data structure – varlena (variable length array).

The varlena structure is defined to hold any kind of data which enables user defined data types, text types, numerics etc. to be stored and used throughout Postgres in a uniform way.

The performance of both varchar(n) and text is pretty much identical. It's difficult to say that it's exactly identical due to system fluctuations. For a more in-depth analysis see this brilliant write up. It's worth noting that using char(n) will actually use more disk space if your string is less characters than n because it will right pad it to specified length.

So which one should we use? The only benefit of using varchar(n) is that is has built-in limit of size, which might come in handy, until you need to change this limit. When upping the limit (which happens quite often), Postgres has to rewrite the entire table. This is bad.

I suggest either using DOMAIN to enforce a maximum length or even cleaner, let your backend handle that before it hits the DB. I therefore prefer text over (n) data types because it lacks their problems, and over its alias, varchar – because it has distinct name and is shorter.

For more information on the data types see https://www.postgresql.org/docs/13/datatype-character.html


Author photo
Cornel Rautenbach
April 20th, 2021