I understand that 2, 4, 8, 16, 32, 64, 128, 256… are the decimal equivalents of binary digits.
Is there a reason why these are used in databases? For example, VARCHAR fields are often 255 characters long. Since (I’m assuming) each character is one byte, why is there a difference between using 255 characters and using 257 characters?
With
varcharcolumns, the length is stored with the data using unsigned integers in the leading bytes of the data. The fewest number of bytes is used; one byte can store lengths from 0 to 255, two bytes from 0 to 65535, etc. By making the length 255, you get the “most value” out of the minimum one length byte.In days gone by, single bytes of disk saved per row were worth saving. Although now disk is cheap, the thinking has remained, especially by grey-haired DBAs.
There is no advantage in choosing a length that is a power of 2, for example
varchar(64)– it is merely a habit/convention (I even follow it – and I don’t know why!).