Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a char occupy 1 byte in a database?

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?

like image 665
5YrsLaterDBA Avatar asked Mar 30 '10 18:03

5YrsLaterDBA


People also ask

How many bytes does a char character take up in MySQL?

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).

Why is a char character equivalent to an 8 bit byte?

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'.

How many bytes does a char field take up?

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.

How many bytes does it take to encode a character?

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.


1 Answers

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

like image 156
Vidar Vestnes Avatar answered Sep 21 '22 15:09

Vidar Vestnes