views:

123

answers:

2

I have heard over and over that you should add indexes to any foreign key you will be doing joins on. I have also heard you should have indexes for fields you will do queries on. Does anyone have a fairly exhaustive list or set of guidelines around when and when not to add indexes?

There must be a size of table where it is inefficient to have indexes. There must be a limit to the number of indexes per table, or why not add an index to every column?

Any resources you can suggest would be very helpful.

Thanks in advance!

+2  A: 

why not add an index to every column

Indexes speed up queries but can slow down inserts and updates. Finding the sweet spot will depend in part on whether your application is likely to do more queries (e.g. a library catalog) or more updates (e.g. an auditing application or log).

JacobM
That makes sense. What about for datetime columns where every value is potentially different?
ChrisH
Again, it depends on whether you're likely to be doing searches based on that column, and on whether you will query more or insert more. There are systems that add rows every millisecond but only get queried a few times a week. They should not be heavily indexed.
JacobM
+1  A: 

Put an index on anything you're likely to join on or sort by. In most cases, it's better to err on the side of more indexes than less, simply because most databases involve more reads than writes, especially web applications. If you were doing financial transactions, it'd be different, but this is a Rails application.

Bob Aman