search
HomeDatabaseMysql TutorialWhy am I getting MySQL Error #1071: Maximum Key Length Exceeded when creating a unique key?

Why am I getting MySQL Error #1071: Maximum Key Length Exceeded when creating a unique key?

MySQL Error #1071: Maximum Key Length Exceeded

When adding a unique key constraint to a MySQL table containing columns with VARCHAR data types, you may encounter the following error:

#1071 - Specified key was too long; max key length is 767 bytes

This error occurs even though the combined length of the VARCHAR columns appears to be less than the maximum key length, which is 767 bytes in MySQL versions 5.6 and prior.

Cause of the Error

The stated prefix limitation for InnoDB tables in MySQL versions 5.6 and below is 767 bytes. This means that the combined length of the key columns' prefixes cannot exceed this limit. For MyISAM tables, the max key length is 1,000 bytes.

In the provided example, the columns column1 and column2 have VARCHAR(20) and VARCHAR(500) data types respectively. This would imply a combined length of 522 bytes, leaving a comfortable margin below the 767-byte limit. However, the error message indicates that this is not the case.

Explanation

The reason for the error is that MySQL uses a variable-length multi-byte encoding for VARCHAR columns. This means that each character in a VARCHAR column can be represented by a varying number of bytes. For example, a VARCHAR(20) column can hold up to 20 characters, but each character can occupy up to 3 bytes if it is encoded in a wide-character format such as UTF-8mb4.

As a result, the actual length of the key is determined by the maximum possible length of the character strings that can be stored in each column. In this case, the maximum possible length of the character strings in column1 and column2 is 20 3 bytes = 60 bytes, and 500 3 bytes = 1500 bytes respectively. This gives a total of 60 1500 = 1560 bytes, which exceeds the maximum key length of 767 bytes.

Solutions

To resolve this issue, you can consider the following solutions:

  • Reduce the maximum lengths of the VARCHAR columns. For example, you could change the data type of column1 to VARCHAR(15).
  • Use a shorter key prefix. Instead of indexing the entire column2 field, you could use only a subset of it, such as column2(200).
  • Use a different table engine that supports longer key lengths. MyISAM tables have a maximum key length of 1,000 bytes, which may be sufficient for your requirements.
  • Upgrade to MySQL version 5.7 or later. MySQL 5.7 and later versions have a maximum key length of 3072 bytes, which provides more flexibility.

The above is the detailed content of Why am I getting MySQL Error #1071: Maximum Key Length Exceeded when creating a unique key?. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.