DEV Community

Discussion on: varchar(n) - how big should n be?

Collapse
 
cubiclesocial profile image
cubiclesocial

VARCHAR is short for "variable CHAR." CHAR(n) is always stored as exactly 'n' characters. VARCHAR(n) uses a size byte preceding the field data so that the stored data doesn't end up with extra whitespace added to it. For n < 256, VARCHAR(n) uses a single byte prefix. Starting at n >= 256, there is a two byte prefix. Other than that, 'n' just tells the database to restrict the maximum number of characters for a field and there is no functional difference other than storage requirements. Depends on the database product as to whether or not it enforces the limit. MySQL/MariaDB will.

If you don't know the exact size of the data, go with VARCHAR(255) or something somewhat larger than your projected field size. I generally use 50, 100, and 255. It won't matter to anyone except pedantic database administrators. Anything larger than VARCHAR(255) should probably be a MEDIUMTEXT field. Anything that's larger than MEDIUMTEXT probably shouldn't be stored in a database unless you enjoy slow database queries that consume lots of disk I/O and CPU usage.