Let’s say I have players table. It consists with 3 rows(it has much more, but let’s suppose it has only 3). member_id, name, exp. I use member_id row in every page so that’s why I added index only to member_id. But I want to make a top players’ list in one page with the highest exp. So I do something like that:
$query = mysql_query("SELECT * FROM players ORDER BY `exp` DESC");
If I have 10k players, I can’t run query like this without adding index to exp. So my question is, should I do like this:
mysql_query("ALTER TABLE `players` ADD INDEX ( `exp` )");
$query = mysql_query("SELECT * FROM players ORDER BY `exp` DESC");
mysql_query("ALTER TABLE `players` DROP INDEX `exp`");
Or there is something else better I can do? Because adding and removing indexes is quite expensive. But probably I could do cache every 10 minutes for example.
Definitely not.
Building an index takes more time than scanning the entire table, so you will severely degrade your performance.
Just build the index once and leave it.