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 the MySQL server, it leaves orphaned records in the InnoDB dictionary. It is annoying because next time you run the same ALTER TABLE query, it will fail with error:

This 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.

A temporary table is a usual InnoDB table except it’s not visible to users. 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 names were random. But they’re 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 a 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 the .frm file must match the structure in the dictionary. It’s not that easy to find out. Fortunately, you don’t need to.

The idea is as follows.

It’s not only DROP TABLE that removes records from the InnoDB dictionary, DROP DATABASE does it too.

In case of DROP TABLE, you need to specify the exact name of the table, while in the case with 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 an 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 the 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