1. Resolving ERROR 1050 42S01 at line 1 Table already exists

Resolving ERROR 1050 42S01 at line 1 Table already exists

When ALTER TABLE crashes MySQL server it leaves orphaned records in InnoDB dictionary. It is annoying because next time you run the same ALTER TABLE query it will fail with error:

The post explains why it happens and how to fix it.

When you run ALTER table InnoDB follows the plan:

  1. Block the original table
  2. Create an empty temporary table with the new structure. The name of the new table is something like #sql-ib712.
  3. Copy all records from the original table to the temporary one
  4. Swap the temporary and original tables
  5. Unblock the original table

The temporary table is a normal InnoDB table except it’s not visible to a user. InnoDB creates a record in the dictionary for the temporary table as for any other table.

If MySQL crashes in the middle of the ALTER process the dictionary ends up with an orphaned table.

We wouldn’t care much if the temporary table name were random. But it’s not and when you run ALTER TABLE again, InnoDB picks up the same name for the temporary table. As long as a record for a table with the same name already exists in the dictionary the subsequent ALTER fails.

How to fix “ERROR 1050 (42S01) at line 1: Table ‘sakila/#sql-ib712’ already exists”

MySQL suggests quite cumbersome method. In short you need to fool MySQL with a fake .frm file so you can DROP the temporary table with an SQL query. It works fine, but the structure of the fake table in .frm file must match the structure in the dictionary. It’s not that easy to find out. Fortunately you don’t need to.

An idea is following.

Not only DROP TABLE removes a records from InnoDB dictionary, DROP DATABASE does it too.

In case of DROP TABLE you need to specify exact name of the table while in case of DROP DATABASE InnoDB will delete all tables for a given database.

To get a clean dictionary for a given database we need to do following:

  1. Create empty temporary database. Let it be tmp1234
  2. Move all tables from the original database to tmp1234
  3. Drop the original database (it’s empty by now, all tables are in tmp1234)
  4. Create the original database again
  5. Move all tables from the temporary database to the original one.
  6. Drop the empty temporary database.

Here’s a script that performs this task. It must be run by root and mysql command should connect to the server without asking the password. Stop all writes to the database before running the script.

Have a question? Ask the experts!

Previous Post Next Post
  • SacTiw

    >>> but the structure of the fake table in .frm file must match the structure in the dictionary
    Here, also make sure the ownership of copied *.frm files are mysql:mysql and not root:root or any other users.

  • yassine slimani

    how to do the same thing but in windows commande line, have you any idea ?