views:

648

answers:

4

In MySQL, if I create a new VARCHAR(32) field in a UTF-8 table does it means I can store 32 bytes of data in that field or 32 chars (multi-byte)?

A: 

32 bytes of data

Chandra Patni
No consensus here... jspcal says 32 multi-byte chars. =\
Alix Axel
+3  A: 

it would let you store 32 multi-byte chars

To save space with UTF-8, use VARCHAR instead of CHAR. Otherwise, MySQL must reserve three bytes for each character in a CHAR CHARACTER SET utf8 column because that is the maximum possible length. For example, MySQL must reserve 30 bytes for a CHAR(10) CHARACTER SET utf8 column.

http://dev.mysql.com/doc/refman/5.0/en/charset-unicode.html

jspcal
I almost never use `CHAR` and when I do it's not intended to store multi-byte chars, so I'm safe. What about `VARCHAR`, are you sure the limit is defined in multi-byte chars and not on single-byte chars?
Alix Axel
yeah varchar seems to work as well
jspcal
@jspcal: UTF-8 uses a maximum of 4 bytes per character, not 3. Or does MySQL not support all 4 bytes?
Remy Lebeau - TeamB
+2  A: 

32 multibytes data for varchar(32) with collation utf8_unicode_ci, I just tested with xampp.

1234567890123456789012345678901234567890

get truncated to

12345678901234567890123456789012
S.Mark
+2  A: 

This answer showed up at the top of my google search results but wasn't correct so:

The confusion is probably due to different versions of mysql being tested.

  • Version 4 counts bytes
  • Version 5 counts characters

http://dev.mysql.com/doc/refman/5.0/en/string-type-overview.html

MySQL interprets length specifications in character column definitions in character units. (Before MySQL 4.1, column lengths were interpreted in bytes.) This applies to CHAR, VARCHAR, and the TEXT types.

Interestingly (I hadn't thought about it) the max length of a varchar column is affected by utf8 as follows:

The effective maximum length of a VARCHAR in MySQL 5.0.3 and later is subject to the maximum row size (65,535 bytes, which is shared among all columns) and the character set used. For example, utf8 characters can require up to three bytes per character, so a VARCHAR column that uses the utf8 character set can be declared to be a maximum of 21,844 characters.

M Brown