Fixing MySQL Invalid Keys
Luke Hebert
- 3 minutes read - 459 wordsCorrupted MYI key files in MySQL can cause queries to fail with “Invalid key” errors, and the usual mysqlcheck repair sometimes isn’t enough. The script below walks through every database owned by the current user, runs a full repair, flags any tables that still report errors, and then forces a rebuild with ALTER TABLE ... USE_FRM.
When to Use This
You’ll hit this situation when:
mysqlcheckreports a table as corrupted but the repair step does not fully fix it.- Queries against a specific table return
ERROR 126 (HY000): Record has been deletedorInvalid keymessages. - The
.MYIindex file is out of sync with the.MYDdata file.
The Repair Script
Run this from the directory that contains the user’s database folders (typically /var/lib/mysql):
user=$(pwd | cut -d'/' -f3)
for db in $(
for i in $(ls /var/lib/mysql | grep "$user_" | grep -v back | cut -d'/' -f1); do
echo "$i"
mysqlcheck -rso "$i"
myisamchk -r "/var/lib/mysql/$i/"*.MYI
done | grep -i "Error" | grep "$user_"
); do
realdb=$(echo "$db" | awk -F. '{print $1}')
table=$(echo "$db" | awk -F. '{print $2}')
echo "ALTER TABLE $table USE_FRM;" | mysql "$realdb"
doneWhat Each Part Does
- Identify the user prefix. The script assumes the working directory path encodes the user name as the third path segment. Adjust the
cutfield if your layout differs. - List candidate databases. It filters
/var/lib/mysqlfor directories matching the user prefix and excludes backup folders. - Repair in place.
mysqlcheck -rsoruns a full repair with verbose output, andmyisamchk -rrebuilds the MYI index file directly. - Capture failures. Only lines containing “Error” that also match the user prefix are passed to the second loop.
- Force a rebuild.
ALTER TABLE ... USE_FRMtells MySQL to reconstruct the table from the.FRMdefinition file, effectively discarding the stale index.
Things to Watch
This script runs ALTER TABLE against every table that still reports an error after the initial repair. Make sure you have a recent backup before running it, especially in production.
- The script assumes MyISAM tables (it targets
.MYIfiles). For InnoDB tables,mysqlcheckandREPAIR TABLEwork differently, andUSE_FRMis not applicable. - If the
grep -i "Error"filter is too broad, you may end up runningALTER TABLEon tables that are actually fine. Review the output ofmysqlcheckfirst if you want a safer pass. - Run the script as the
mysqlsystem user or a user with sufficient privileges to access/var/lib/mysql.
Verifying the Fix
After the script completes, re-run a quick health check:
mysqlcheck -s --all-databasesAll tables should report OK. If any still show errors, investigate the specific table with SHOW TABLE STATUS and consider a full mysqldump / DROP / RESTORE cycle for that table.