0

I have already checked what is the reason of this error. Therefore, I know I am exceeding the limit (767 byte) by trying to set email VARCHAR(320) as a UNIQUE key (320 * 3 = 960 byte).

However, I am using MySQL as a database and I need to use the email value as a unique key in my application. Could you please tell me, what should I change to overcome this problem?

Kaan Burak Sener
  • 974
  • 10
  • 19

2 Answers2

1

Create a unique index on the first 254 characters or so:

create unique index idx_t_email on t(email(254));

Emails should be shorter than 254 characters.

According to this answer, the longest possible email is 254 characters anyway, so this should be fine.

Community
  • 1
  • 1
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Why not use a trigger to calculate a hash of the mail column, then save the hash as unique field? `sha1` is 20 bytes long so a `binary(20)` can be used to hold it. It spends less space and it can be automated as well.. – N.B. Mar 31 '16 at 16:18
1

Assuming you are using MySQL 5.5.14 or newer, you can solve this problem by:

  • Enabling the innodb_large_prefix server setting
  • Enabling innodb_file_format = BARRACUDA
  • Using ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED

This will allow you to include columns up to 3072 bytes long in InnoDB indexes, so your 320 character column could be included in a unique index.

Read my blog post for more details:

http://mechanics.flite.com/blog/2014/07/29/using-innodb-large-prefix-to-avoid-error-1071/

Ike Walker
  • 64,401
  • 14
  • 110
  • 109