What's the difference between the text
data type and the character varying
(varchar
) data types?
According to the documentation
If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.
and
In addition, PostgreSQL provides the text type, which stores strings of any length. Although the type text is not in the SQL standard, several other SQL database management systems have it as well.
So what's the difference?
The short answer: there is no difference. The long answer: CHARACTER VARYING is the official type name from the ANSI SQL standard, which all compliant databases are required to support. (SQL compliance Feature ID E021-02.) VARCHAR is a shorter alias which all modern databases also support.
CHAR items, which are fixed length, are the fastest to store and retrieve but can waste storage space. VARCHAR, a variable-length string, can be slower to store and retrieve but does not waste storage space. TEXT is a character BLOB that requires more storage space and I/O than the other two.
Difference between CHAR and VARCHAR datatypes: 1. 2. In CHAR, If the length of the string is less than set or fixed-length then it is padded with extra memory space. In VARCHAR, If the length of the string is less than the set or fixed-length then it will store as it is without padded with extra memory spaces.
The CHARACTER VARYING data type stores a string of letters, digits, and symbols of varying length, where m is the maximum size of the column (in bytes) and r is the minimum number of bytes reserved for that column.
There is no difference, under the hood it's all varlena
(variable length array).
Check this article from Depesz: http://www.depesz.com/index.php/2010/03/02/charx-vs-varcharx-vs-varchar-vs-text/
A couple of highlights:
To sum it all up:
- char(n) – takes too much space when dealing with values shorter than
n
(pads them ton
), and can lead to subtle errors because of adding trailing spaces, plus it is problematic to change the limit- varchar(n) – it's problematic to change the limit in live environment (requires exclusive lock while altering table)
- varchar – just like text
- text – for me a winner – over (n) data types because it lacks their problems, and over varchar – because it has distinct name
The article does detailed testing to show that the performance of inserts and selects for all 4 data types are similar. It also takes a detailed look at alternate ways on constraining the length when needed. Function based constraints or domains provide the advantage of instant increase of the length constraint, and on the basis that decreasing a string length constraint is rare, depesz concludes that one of them is usually the best choice for a length limit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With