Sunday, September 16, 2018

Why is Varchar(255) in MySQL when 2^8 is 256?

If you look in many database implementations, you will see that VARCHAR limits are not at 256 (2^8), but they are at 255.

This 255/256 value is the number of characters storeable in the field. If the index starts at the 1st character, you would think that it should end at the 256th character, because 2^8 = 256.

According to the MySQL documentation, the size of a varchar field is actually "1 + (0 to 255 bytes)", or "2 + (256 to X bytes", if over 255.

Source: https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html

That delimiting mark, between 255 and 256 bytes, is defined not by logical limitations of data storage, but by the MySQL implementation itself. By using the 255 limit, you are using one less byte than if you had 256.

This is so that MySQL can count the length of a field (from 0 to 255, not from 1 to 256) in a single byte.

Be aware, though: If any of the characters are UTF-8, that means they will be multi-byte encoded, and this will definitely go over the 255 byte limit in MySQL and use the extra byte, even if it doesn't warn you of that.

No comments:

Post a Comment