Lee Packham’s Corner
The rants of a software busy body
  • Home
  • Gallery
  • About
  • dtrace Stuff

Big table and changing indexes

MySQL Add comments

MySQL sucks at large tables. Sorry if you’ve come here thinking that I, in any way, like MySQL. That said, I have to look after some sizeable databases which are on MySQL for various reasons - so needs must.

I recently needed to sort out an issue with indexes on a table. I needed to drop one, and add a couple more. Snag? The table has 3.6 million rows and as such I would call it a large table.

Normally, I guess, you would do something like:

ALTER TABLE foo ADD INDEX (my_column);
ALTER TABLE foo DROP INDEX old_index;

This doesn’t work when you have a lot of rows. Well, it does… if you have a few hours to spare. Let’s look at why.

When you add an index to a pre-existing table, MySQL has to go look through the entire table to populate the new index. When you drop an index on a pre-existing table, it loops through every row depopulating the index before finally dropping it.

So, here’s what I did to speed things up:

  1. SELECT * FROM foo INTO OUTFILE 'foo_outfile.dmp';
  2. CREATE TABLE foo_a LIKE foo;
  3. ALTER TABLE foo_a ADD INDEX (my_column);
  4. ALTER TABLE foo_a DROP INDEX old_index;
  5. LOAD DATA INFILE 'foo_outfile.dmp' INTO TABLE foo_a;
  6. TRUNCATE TABLE foo; DROP TABLE foo;
  7. ALTER TABLE foo_a RENAME foo;

Why TRUNCATE before DROP? That’s easy, DROP tries to delete each row. To delete each row the index has to be updated… 3.6M times! TRUNCATE trashes everything, then you’re dropping an empty table!


September 29th, 2008 |

Leave a Reply

  • Friend's Blogs/Sites

    • David Rickard
    • Lloyd Pick
    • Michael Smith
  • Recent Posts

    • Is it any wonder the world is infested with spam?
    • The Wowhead Christmas Wallpaper
    • Unibody Macbook Pro constantly waking up
    • How Warcraft reigned supreme in 2008
    • CRY vs. DRY
  • Archives

    • January 2009
    • December 2008
    • November 2008
    • October 2008
    • September 2008
    • August 2008
    • July 2008
    • June 2008
    • May 2008
    • April 2008
    • March 2008
    • November 2007
    • October 2007
    • August 2007
    • July 2007
    • June 2007
    • May 2007
    • January 2007
    • December 2006
    • October 2006
    • September 2006
  • Recent Tracks (last.fm)

    • Nickelback – Gotta Be Somebody 16 hours ago
    • Nickelback – Burn It to the Ground 16 hours ago
    • Nickelback – Something in Your Mouth 16 hours ago
    • Lisa Miskovsky – Still Alive (The Theme from Mirror's Edge) (Paul Van Dyk Mix) 16 hours ago
    • The Prodigy – Charly 20 hours ago
  • Meta

    • Log in
    • Entries RSS
    • Comments RSS
    • WordPress.org
Copyright © 2009 Lee Packham’s Corner All Rights Reserved
RSS XHTML CSS Log in
Wp Theme by n Graphic Design
Powered by Wordpress