could anyone tell me what are the reasons for adding an index to a table?

Performance, mainly - it essentially allows you to do

Code:
SELECT foo FROM bar WHERE baz = 'flobalob'

Without having to do a full table scan to find the row in which baz is flobalob.
 
The simplest explanation for this is to think of it just like an index at the back of a book. It allows you to quickly find specific items. Rather than searching through the whole book for a particular phrase or word, you would check the index for the pages you need to look up and examine.
 
MySQL Manual said:
7.4.5. How MySQL Uses Indexes

Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. If a table has 1,000 rows, this is at least 100 times faster than reading sequentially. If you need to access most of the rows, it is faster to read sequentially, because this minimizes disk seeks.
Essentially indexes are used much like the index in a phone book - it's much quicker to find something if you know where to look.

As for what the indexes should be, it's fairly easy - just index the most-used column(s) (you can have more than one column in an index) in your table - but don't add too many because you'll waste disk/memory space :)

The MySQL site has a huge page on indexes here so I won't go on but if you get stuck just post away :)
 
Back
Top Bottom