In an Twitter exchange, Simon West asks to Brandur,
Out of interest, why do use
email TEXT CHECK (char_length(email) <= 255)
rather thanemail VARCHAR(255)
? Not a pattern I've seen before
Brandur responds,
Excellent question!
(1) VARCHAR and TEXT are equally performant in Postgres (see the "tip" box at https://www.postgresql.org/docs/current/static/datatype-character.html …).
.(2) If you ever want to change the length,
ALTER TABLE
requires an exclusive lock (see https://www.postgresql.org/docs/current/static/sql-altertable.html …). ChangingCHECK
is instant.
When answering a question that called into questiontext CHECK (char_length(email) <= 255)
vsvarchar(255)
Is the first claim (bolded) of the two claims made strictly true?
If interested in the second claim check out this question.
Best Answer
No, it's not strictly true. Here is what the linked docs say,
So essentially
varchar
overtext
when the column is unconstrained. This is not true in some databases, namely ones that implement schemes likeVARCHAR(max)
.varchar(x)
overtext CHECK ( length(x) <= x)
Example
You can easily see this,
Note,
char_length
andlength
are the same here. They internally calltextlen
.Results
In each case, the insert into
bar
is slowerType-constraints rechecked
I would have though too that the checks would have carried over to tables using the same types. This kind of optimization may be possible some day, but alas no joy,
Though the varchar form is still noticeably faster.
Other Notes
As it relates to emails the subject of the tweet, this post may also be useful.