0
CREATE SCHEMA IF NOT EXISTS `utftest`  DEFAULT CHARACTER SET utf16;
CREATE  TABLE IF NOT EXISTS `metadata_labels` (`metadata_id` INT NOT NULL , `label` VARCHAR(256) NOT NULL ,  PRIMARY KEY (`metadata_id`, `label`));

however I get the following error msg:

Specified key was too long; max key length is 767 bytes

Please advise

2
  • Just tested this and it seems to work fine? Commented Feb 12, 2013 at 23:45
  • If possible, you should use an auto incrementing integer or GUID instead of a very long varchar as primary key Commented Feb 12, 2013 at 23:47

2 Answers 2

1

UTF 16 uses 32 bits per character (4 bytes) in MySQL. 4 x 256 > 767.

If possible, I would recommend using something other than UTF16 VARCHAR for your key.

Sign up to request clarification or add additional context in comments.

3 Comments

so what are options? i need to use UTF to support international characters and special characters.......
Is this required for the key?
yea, we need to support international characters in the metadata_labels.label
1

In UTF8, it would require 3 x 256 + 4 = 772 bytes. UTF16 would take another 25% more.

You shouldn't use a primary key that's so wide; for an index to be efficient, the storage for each index should be kept to a minimum.

If you need to prevent duplicates, I would recommend adding a calculated field that contains a hash of the contents (e.g. sha1) and create a unique constraint on that instead.

Alternatively, use latin1 as the character encoding for the label field to reduce the number of bytes to 256 + 4 = 300.

If Unicode is a must and hashes are out of the picture you should reduce the column to either UTF8 (250 chars) or UTF16 (190 chars)

5 Comments

@JasonMcCreary utf8 may require between 1 and 3 bytes of storage for each character.
is there is a way where i don't have to add another field(hash)?
@SaqibAli You could try to reduce the field width down to 250.
The question references utf16 which is 4 bytes.
Thanks @Jack. I have done that for now. But we will need to figure out a better DB schema

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.