Ошибка incorrect key file for table

First of all, you should know that keys and indices are synonyms in MySQL. If you look at the documentation about the CREATE TABLE Syntax, you can read:

KEY is normally a synonym for INDEX. The key attribute PRIMARY KEY can also be specified as just KEY when given in a column definition. This was implemented for compatibility with other database systems.


Now, the kind of error you are getting can be due to two things:

  • Disk issues on the MySQL server
  • Corrupted keys/tables

In the first case, you will see that adding a limit to your query might solve the problem temporarily. If that does it for you, you probably have a tmp folder that is too small for the size of the queries you are trying to do. You can then decide or to make tmp bigger, or to make your queries smaller! ;)

Sometimes, tmp is big enough but still gets full, you’ll need to do some manual cleanup in these situations.

In the second case, there are actual issues with MySQL’s data. If you can re-insert the data easily, I would advice to just drop/re-create the table, and re-insert the data. If you can’t you can try repairing the table in place with REPAIR table. It is a generally lengthy process which might very well fail.


Look at the complete error message you get:

Incorrect key file for table ‘FILEPATH.MYI’; try to repair it

It mentions in the message that you can try to repair it. Also, if you look at the actual FILEPATH you get, you can find out more:

  • if it is something like /tmp/#sql_ab34_23f it means that MySQL needs to create a temporary table because of the query size. It stores it in /tmp, and that there is not enough space in your /tmp for that temporary table.

  • if it contains the name of an actual table instead, it means that this table is very likely corrupted and you should repair it.


If you identify that your issue is with the size of /tmp, just read this answer to a similar question for the fix: MySQL, Error 126: Incorrect key file for table.

Summary:
This blog discusses the MySQL error ‘Incorrect Key File for Table’ in detail. It describes possible causes behind the error and solutions to fix them. To fix the error caused due to corrupted tables, try using Stellar Repair for MySQL software. Use the software’s demo version to repair the database and its corrupt tables, and preview the recoverable tables to check data integrity.

Free Download for Windows

Free Download for Windows

Contents

  • Why Does MySQL Return ‘Incorrect Key File for Table’ Error When Running a Query?
  • Possible Causes Behind MySQL Error’ Incorrect Key File for Table’ and Their Solutions
  • Conclusion

You may encounter the MySQL error ‘Incorrect Key File for Table’ when running a large MySQL query. For instance, some users have reported receiving the error while executing a query to fetch thousands of records from a table using more than one JOIN.

Why Does MySQL Return ‘Incorrect Key File for Table’ Error When Running a Query?

The complete MySQL error message “Incorrect key file for table ‘FILEPATH.MYI’; try to repair it” suggests that you can try to repair the key. Looking at your table FILEPATH can help you find more details about the error:

  • If the FILEPATH looks similar to ‘/tmp/#sql_xxxx.MYI‘, it means that your query is returning a large result set. The/tmp folder used for storing a temporary table containing the larger result set is too small for the query size. Essentially, there is not sufficient space in your /tmp folder for the temporary table.
  • If your FILEPATH contains the database table’s name, it’s likely that your table is corrupt.

Possible Causes Behind MySQL Error’ Incorrect Key File for Table’ and Their Solutions

You may be getting the error because of a disk space issue or corruption in MySQL table. Read on to know how you can resolve these two issues.

Cause 1 – Insufficient Disk Space in the Temporary Folder (/Tmp)

Note: You won’t get the error on executing individual queries, but you may encounter the error when running large queries simultaneously on the same MySQL Server.

The primary reason that results in MySQL ‘Incorrect key file’ error is that your query is fetching data greater than the size of your /tmp folder (i.e., the folder used for storing temporary tables).

Solution – Change the location of ‘/temp’ folder

First of all, you must determine if the disk partition is full by looking at your /tmp folder size. Run the df command with ‘-h‘ option to check disk usage of the file system in human-readable form:

df –h

If the partition is full, then change the location of the /tmp folder to a disk with ample free space. Change the file location in the MySQL configuration file (.cnf).

Sometimes, the /tmp folder is big enough, but it might still get full. In that case, you will need to clean up some space in the folder manually.

Cause 2 – Corrupted Keys or Table

Table corruption is another reason that may lead to the ‘Incorrect Key File for Table’ error.

Solution – Re-create or Repair the Corrupted Table

To resolve the issue, drop/re-create the corrupt table and then re-insert the data.

For example, in the following query ‘DELETE’ operation is used for dropping the table, and ‘OPTIMIZE’ TABLE command is used afterward to free disk space.

mysql> DELETE tbl_name WHERE id < 200000;

mysql> OPTIMIZE TABLE tbl_name;

If you cannot re-insert the data, try repairing the table. For MyISAM tables, you can use the ‘REPAIR table’ command to fix the corruption:

REPAIR TABLE tbl_name USE_FRM;

This command will work only on MyISAM tables. For repairing tables with InnoDB database engine, check out the best ways to repair InnoDB table corruption in MySQL. But, running a repair command for each of the tables in the query can be a lengthy and time-consuming process.

What Else You Can Do to Repair Corrupt Tables?

Use Stellar Repair for MySQL software to repair corrupt tables. The software helps repair MySQL database and all its objects quickly in just a few clicks. It recovers all data from the corrupted database without data loss.

Conclusion

When you encounter the MySQL error ‘Incorrect Key File for Table’, the first thing you should do is to check the location of /tmp folder to ensure that it has enough disk space to store temporary tables. If not, then change the folder location to a disk having ample free space. If there is no issue with disk space, chances are that your database table is corrupt and needs to be repaired. If you fail to repair the table manually, using MySQL database repair software can help.

About The Author

Charanjeet Kaur

Charanjeet is a Technical Content Writer at Stellar®who specializes in writing about databases, e-mail recovery, and e-mail migration solutions. She loves researching and developing content that helps database administrators, organizations and novices to fix multiple problems related to MS SQL and MySQL databases and Microsoft Exchange.

What does it mean if MySQL returns the ‘Incorrect key file for table’ error for one of my queries? The answer is complicated and depends on which storage engine is returning the error. We have debugged two cases which we describe here.

File system out of space

When running the random query generator, one of the queries failed.

<span class=«inner-pre» style=«font-size: 12px;»>Query: SELECT * FROM (mysql . general_log AS table1 INNER JOIN INFORMATION_SCHEMA . INNODB_BUFFER_PAGE AS table2

ON ( table2 . SPACE = table1 . user_host ) ) ORDER BY table1 . thread_id LIMIT 168

failed: 126 Incorrect key file for table ‘/data/mysql7/performance_schema_vardir/tmp/#sql_6b8_17.MYI’;

try to repair it</span>

Since this query requires a sort, MySQL creates a hidden temporary table called ‘#sql_6b8_17.MYI’ to hold the intermediate results. While the query was executing, some operation performed on the MyISAM table returned an error. What could it be?

MySQL maps the HA_ERROR_CRASHED error received from the storage engine to the ER_NOT_KEYFILE error that the MySQL client sees. We need to track down where MyISAM returns the HA_ERROR_CRASHED error. Unfortunately, the MyISAM storage engine has lots of places where it returns HA_ERROR_CRASHED, so the cause can be almost anything.

In our case, we found that the MyISAM mi_write function eventually got an ENOSPC (no space) error when trying to write data to one of its files. The file system ran out of space. In this case, MyISAM returns the HA_ERROR_CRASHED error, the MySQL client gets the ER_NOT_KEYFILE error, and the random query generator notes the failed query. Simple, right?

Race in secondary index query

TokuDB returns the HA_ERROR_CRASHED error when it can not read a row from the primary index using a primary key that it read from a secondary index. What does that mean?

Each key defined for a TokuDB table is stored in a fractal tree dictionary. The fractal tree for the primary key is stored in the ‘main’ fractal tree dictionary. If the table does not define a primary key, then TokuDB manufactures a hidden primary key and uses it as the primary key. This hidden primary key is never seen outside of the TokuDB storage engine. Each secondary key is stored in its ‘key’ fractal tree dictionary. The key into these dictionaries is composed of the columns of the secondary key and the columns of the primary key appended to it.

Given this mapping, non-covering queries read the secondary index first and then read the primary index using the primary key read from the secondary index.

Lets suppose that we have a simple table.

<span class=«inner-pre» style=«font-size: 12px;»>mysql> show create table t;

CREATE TABLE `t` (

  `x` int(11) DEFAULT NULL,

  `y` int(11) DEFAULT NULL,

  KEY `x` (`x`)

) ENGINE=TokuDB DEFAULT CHARSET=latin1 ROW_FORMAT=TOKUDB_ZLIB</span>

We insert a single row into the table

<span class=«inner-pre» style=«font-size: 12px;»>mysql 1> insert into t values (1,2);

Query OK, 1 row affected (0.00 sec)</span>

On another MySQL client, we will run a query and force it to use the secondary key for ‘x’. Since it is not a covering key for the query, TokuDB will read a row from the secondary key and use the primary key that was retrieved to read a row in the primary hidden dictionary. We are going to put a delay between these two events and see what happens.

We use read uncommitted isolation level.

<span class=«inner-pre» style=«font-size: 12px;»>mysql 2> set session transaction isolation level read uncommitted;

Query OK, 0 rows affected (0.00 sec)</span>

We set a debug variable that forces a delay between reading a row from the index on ‘k’ and then using the retrieved primary key to read the full row from the hidden primary index.

<span class=«inner-pre» style=«font-size: 12px;»>mysql 2> set tokudb_read_full_row_delay=10000000;</span>

Now, we start the query. It should stall the thread in the read_full_row method for the delay time.

<span class=«inner-pre» style=«font-size: 12px;»>mysql 2> select * from t force index (x) where x>0;

blocked sleeping</span>

On the other MySQL client, we delete the row.

<span class=«inner-pre» style=«font-size: 12px;»>mysql 1> delete from t where x=1;

Query OK, 1 row affected (0.00 sec)</span>

Eventually, the query client resumes after the sleep completes and can no longer find the primary key in the primary fractal tree, so it returns the HA_ERR_CRASHED error.

<span class=«inner-pre» style=«font-size: 12px;»>mysql 2> resumes after the sleep completes

ERROR 1034 (HY000): Incorrect key file for table ‘t’; try to repair it</span>

This problem does not occur for any other transaction isolation levels as far as we know. This is because TokuDB uses snapshot reads when reading MVCC leaf entries for all transaction isolation levels other than read uncommitted. For read uncommitted transaction isolation level, TokuDB just returns the latest MVCC entries from the leaf entry, which may be inconsistent with the rest of the table.

Maybe, TokuDB should silently eat this error for read uncommitted queries. What do you think?

Skip to content

При добавлении элементов таблиц через PHPMYADMIN (полей или столбцов) может появляться ошибка #1034 — Incorrect key file for table ‘table_name’; try to repair it .

Часто может также наблюдаться повышенная нагрузка создаваемая на CPU или диск сервером баз данных.

Причиной часто может быть нехватка места в разделе mysqltmp в котором сохраняются временные данные MySQL.

Выяснить объем диска, выделенные под временные файлы MySQL можно выполнив в консоли команду df -h

df -h

Filesystem Size Used Avail Use% Mounted on
udev 10M 0 10M 0% /dev
tmpfs 818M 1.2M 817M 1% /run
/dev/vda 148G 124G 18G 88% /
/dev/vdb 175M 175M 0 100% /lib/modules
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 1.6G 0 1.6G 0% /run/shm
mysqltmp 128M 0 128M 0% /var/tmp-mysql

В примере под mysqltmp выделено 128 Мб, чего может быть недостаточно. Перемонтируем раздел добавив пространства

mount -o remount,size=1G /var/tmp-mysql/

df -h

Filesystem Size Used Avail Use% Mounted on
udev 10M 0 10M 0% /dev
tmpfs 818M 1.2M 817M 1% /run
/dev/vda 148G 124G 18G 88% /
/dev/vdb 175M 175M 0 100% /lib/modules
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 1.6G 0 1.6G 0% /run/shm
mysqltmp 1.0G 48K 1.0G 1% /var/tmp-mysql

Сейчас доступен 1 Гб.

Если ошибки #1034 — Incorrect key file for table ‘table_name’; try to repair it продолжают появляться нужно редактировать значения двух указанных ниже переменных в конфигурационном файле /etc/mysql/my.cnf или в одном из файлов, который подключается в /etc/mysql/my.cnf .

Директивы добавляются в секцию [mysqld]

tmp_table_size
max_heap_table_size

Значения увеличиваются до тех пор пока ошибки появляться не перестанут.

После того как конфигурационный файл отредактирован сервер баз данных нужно перезапустить

systemctl restart mysql

Читайте также про оптимизацию настроек MySQL

use Google Translate

Last update: 07-04-2016

Summary:

The MassTransit Engine may inadvertently shut down, and will not properly restart. Within the Application Log of the Windows Event Viewer, the following error message may be displayed:

SA_Exception[xxxx]: DB_Files_Edit: Incorrect key file for table ‘tablename‘; try to repair it.
Commonly, tablename may be referenced as ‘dfiles’

Description:

This error indicates that the table listed within the error message has become corrupt, and must be repaired. In most cases, the table can easily be fixed with through the MySQL command line. Follow this procedure to repair failed tables:

  1. Open a Windows command prompt
  2. Navigate to the MySQL monitor command-line utility, which may be found at this location: C:Program FilesMySQLMySQL Server X.Xbin
  3. Invoke the MySQL monitor utility with the following command: mysql -uroot -p
  4. Enter your root password as specified during the initial installation of MySQL server.
  5. After successfully logging in, you should see a ‘mysql>’ prompt.
  6. At the ‘mysql>’ prompt, type the command: repair table tablename quick;
    NOTE: tablename should be the name of the table listed in the Event Viewer error message, such as dfiles. Note also that the semi-colon character (;) at the end of the statement is required.
  7. When the repair process is completed, the results of the process will be displayed within the terminal.
  8. You may now close your terminal window.

The status message should indicate that the repair status was successful by indicating «OK.» If any further errors result, it is important to contact Group Logic technical support for additional troubleshooting and repair instructions. After a successful repair has been completed, you may now be able to restart your MySQL Service, followed by the MassTransit Engine Service.

Теги: 

  • Key
  • GroupLogic

Понравилась статья? Поделить с друзьями:
  • Ошибка inaccessible boot device при загрузке windows 10
  • Ошибка in5p опель астра что это
  • Ошибка in use on this server
  • Ошибка http 400 честный знак
  • Ошибка http 400 размер заголовков запроса слишком длинный