Home >Database >Mysql Tutorial >How to Solve the 'Specified Key Was Too Long; max key length is 1000 bytes' Error in MySQL?
Handling "Specified Key Was Too Long" Error for Index Definition
The error message "Specified key was too long; max key length is 1000 bytes" indicates an issue with the length of the index defined for a table. This error can occur even if the query has worked successfully in the past, as it can be influenced by factors such as the database server version, index type, and column data.
In the provided query:
CREATE TABLE IF NOT EXISTS `pds_core_menu_items` ( ... KEY `index` (`parent_menu_id`,`menu_link`,`plugin`,`alias`) ... )
The index index is defined on four columns: parent_menu_id, menu_link, plugin, and alias. The combined length of these columns exceeds 1000 bytes, resulting in the error.
To resolve this issue, there are several approaches:
1. Reduce Index Column Length:
The most straightforward way to fix the error is to reduce the length of the index columns. This can be done by using prefix indexes, where only a portion of the column data is indexed. For example:
KEY `index` (`parent_menu_id`,`menu_link`(50),`plugin`(50),`alias`(50))
Prefix indexes are recommended because they significantly reduce the index size while still maintaining efficient lookups.
2. Determine Optimal Prefix Length:
To determine the optimal prefix length for each column, it's helpful to analyze the data distribution using a query like:
SELECT ROUND(SUM(LENGTH(`menu_link`)<10)*100/COUNT(`menu_link`),2) AS pct_length_10, ROUND(SUM(LENGTH(`menu_link`)<20)*100/COUNT(`menu_link`),2) AS pct_length_20, ROUND(SUM(LENGTH(`menu_link`)<50)*100/COUNT(`menu_link`),2) AS pct_length_50, ROUND(SUM(LENGTH(`menu_link`)<100)*100/COUNT(`menu_link`),2) AS pct_length_100 FROM `pds_core_menu_items`;
This query provides the percentage of rows with the column value less than a specific length. Based on these results, you can select the appropriate prefix length to minimize the index size while maintaining good performance.
Additional Considerations:
It's important to note that the error can also occur if the total length of the index exceeds 1000 bytes, even if all individual columns are shorter than 1000 bytes. Therefore, when defining indexes on multiple columns, the combined length should be considered.
Furthermore, the INT(1) and INT(32) data types are not relevant to the index length issue. However, it's worth noting that the numeric argument in these data types does not affect storage or value ranges, but rather formatting during display.
The above is the detailed content of How to Solve the 'Specified Key Was Too Long; max key length is 1000 bytes' Error in MySQL?. For more information, please follow other related articles on the PHP Chinese website!