When I executed the following command:
ALTER TABLE `mytable` ADD UNIQUE (
`column1` ,
`column2`
);
I got this error message:
#1071 - Specified key was too long; max key length is 767 bytes
Information about column1 and column2:
column1 varchar(20) utf8_general_ci
column2 varchar(500) utf8_general_ci
I think varchar(20)
only requires 21 bytes while varchar(500)
only requires 501 bytes. So the total bytes are 522, less than 767. So why did I get the error message?
#1071 - Specified key was too long; max key length is 767 bytes
If you're creating something like:
it should be something like
but you need to check uniqueness of that column from code or adding a new column as an MD5 or SHA1 of the varchar column
run this query before your query:
this will increase limit to
3072 bytes
.In my case, I had this problem when I was backing up a database using the linux redirection output/input characters. Therefore, I change the syntax as described below. PS: using a linux or mac terminal.
Backup (without the > redirect)
Restore (without the < redirect )
The error "Specified key was too long; max key length is 767 bytes" simple disappeared.
If anyone is having issues with INNODB / Utf-8 trying to put an
UNIQUE
index on aVARCHAR(256)
field, switch it toVARCHAR(255)
. It seems 255 is the limitation.In case that you run Laravel (laravel now defaults to 4 byte Unicode which causes this) you can solve this by changing next lines in config/database.php from
 to
For me, the issue of "#1071 - Specified key was too long; max key length is 767 bytes" got resolved after changing the primarykey / uniquekey combination by limiting the column size by 200.