views:

38

answers:

2
+1  Q: 

Mysql optimization

I have this mysql table called comments which looks like this:

commentID parentID type userID date comment

The commentID is set as Primary key, but most of the time I fetch the data using the parentID. How should I set my indexes?

Should I just add an index on parentID and let commentID be the primary key?

Edit: Would it be bad to have 3 indexes? For example on a forum table which has a categoryID boardID and topicID?

A: 

Basically the bad thing about having many indexes are slower INSERT, UPDATE and DELETE operations because it changes the index tree, but faster SELECT if you use the indexes.

I don't think it's bad, if you can afford it.

Dmitry Yudakov
+1  A: 

If you have a query like select * from comments where parent_id = ... order by date desc or something like that, you should create (in addition to the primary key) an index on (parent_id, date), which is a single index over two columns. The first part of the index is used by the where clause and the second one ensures, that the filtered entries are in the correct order, so that no time-consuming sorting is needed.

There is no need to create an index on a primary key only. The primary key is used for the internal storage and already extremely fast. You will need that quite often for joins.

You can add many indexes to a single table, but indexes will slow down the time of a update or a delete. Therefore, you should try to only have a maximum of 4-5 indexes per table.

tux21b