Does a char occupy 1 byte in a database?
EDIT: If I define a column as varchar(1), will it reserve 1 or 2 bytes for me?
CHAR (n) -- Depending on the vintage of your copy of MySQL and the ROW_FORMAT, CHAR may allocate a full 3 bytes per character. VARCHAR (n) -- This will occupy one or two bytes for a length, plus only as many bytes are needed. That is each character will occupy 1, 2, or 3 bytes for the CHARACTER SET utf8 (utf8mb3).
At the time, all character sets in use would have a character that fit in an 8 bit byte, and the primary use for 8-bit types was for storage of characters. Thus, C defined 'char' to be equivalent to 'byte'.
Yes, if you specify the length of the char field as one, and the database is using a codepage based character mapping so that each character is represented as one byte. If the database for example is set up to use UTF-8 for storing characters, each character will take anything from one to five bytes depending on what character it is.
Yes, 1 byte does encode a character (inc spaces etc) from the ASCII set. However in data units assigned to character encoding it can and often requires in practice up to 4 bytes. This is because English is not the only character set. And even in English documents other languages and characters are often represented.
Char(k) takes k-bytes no matter what the value is, varchar(k) n+1 bytes, where n = number of chars in the value, but max k+1 bytes
Value CHAR(4) Storage Required VARCHAR(4) Storage Required
'' ' ' 4 bytes '' 1 byte
'ab' 'ab ' 4 bytes 'ab' 3 bytes
'abcd' 'abcd' 4 bytes 'abcd' 5 bytes
'abcdefgh' 'abcd' 4 bytes 'abcd' 5 bytes
http://dev.mysql.com/doc/refman/5.1/en/char.html
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