VARCHARS: 2, 4, 8, 16, etc.? Or 1, 3, 7, 15, etc.?

I see that VARCHAR (255) is used all the time instead of VARCHAR (256), but I also use VARCHAR (16) instead of VARCHAR (15). It seems inconsistent to me. If an extra byte is used to store the VARCHAR length, should this rule not apply to smaller sizes, for example, 2, 4, 8 instead of 1, 3, 7?

Or am I missing something?

In other words, if I have a number that I know will never be higher than 12, should I go further and use VARCHAR (15) or VARCHAR (16) instead? Because it uses the same space as VARCHAR (12)? If so, which one am I using? 15 or 16? Does this rule change at all when I approach 256?

I use MySQL and SQL, depending on the project.

+4
source share
3 answers

In other words, if I have a number that I know will never be higher than 12, should I just use VARCHAR (15) or VARCHAR (16) instead?

No! Use varchar (12) (or perhaps even char (12) if the length is pretty constant).

The varchar type was once limited to 255 characters on some systems ( including MySql to 5.0.3 ), since the first byte indicated is the length of the field. Given this limitation, developers who want to allow a reasonable amount of text would choose 255 instead of going to another type of data at all.

But if you know the size of your data, definitely use that size for the database.

+10
source

This has nothing to do with odd or even numbers.

Historically, 255 characters have often been the maximum length of VARCHAR in various DBMSs. The length limit for a field that was not LOB (Large Object) was then 255 bytes (1 byte int). Thus, the first byte was used to store the field length (0-255) and the remaining n bytes for characters. That is why you often see VARCHAR(255) .

If the field will never be greater than 12, use VARCHAR(12) .

+4
source

I think the original problem is that for some systems, VARCHAR (...) was limited to 255, because when you use one byte to encode the actual length, you can only express lengths up to 255.

VARCHAR (16) / VARCHAR (15) most likely resembles these sources, but there is nothing special in the two meanings.

+2
source

All Articles