I just found out that in order to prevent full table scans during joins, I need to add indexes to my foreign keys in my rails app. But I’m unsure exactly what adding indexes to foreign keys means, how it works, and how it boosts performance.
Share
I think wikipedia has a good summary of what indexes are and do. See here: http://en.wikipedia.org/wiki/Index_%28database%29
Indexes can/do increase the size of the database. They effectivily cache an order for your data. When you index with respect to a foreign key relationship you are going to cache default ordering for your table which can reduce the size of the items that need to be searched in your table or can speed up joins.
Consider this contrived example:
I have a table called employee:
Employee ID | Employee code | Employee Name
1 | 0003 | Richard
2 | 0002 | Bob
3 | 0008 | Tim
I want to join to a sorted list of employee codes:
0003
0008
This will mean without indexes you have efficiency of search of O(n2). With the table ordered by Employee Code, you can see a search efficency given by a binary search tree: http://en.wikipedia.org/wiki/Binary_search_algorithm . Effectively it can find 0003 by guessing its location and finding it getting forever closer, as opposed to searching every single row.
Im not saying that your database is using any particular algorithm, but there are algorithms that require ordering of data by keys in order to do more efficient searches.
You probably want to consider removing indexes when you no longer require them too, since it impacts database size.