Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Owen Abbott4,776 Points
confused about the difference between adding a foreign key and indexing.
I'm new to this site and brand new to programming in general. I'm learning rails development, and when explaining hot to create associations between models, the video says we add a foreign key and also an "index." It says we can function with just foreign keys, but that indexing is faster and standard.
I can conceptualize what a foreign key looks like and how it creates an association, but I'm pretty hazy on what 'indexing' looks like or does.
Jade Steffen1,842 Points
Hey Owen, great question.
It sounds like you know a bit about what Foreign Keys are, but what about indexes? An index is a bit of an optimization tool. It allows the database to search and sort the table on the foreign key ids.
So, if you ask the database for all the Children belong to a given Parent, it will be able to use the foreign key ID as an index into the table. Because it has created an index for parent Id's, much like the index to a book, this information is readily available. The alternative would be for the database to go through every row and see if it's foreign key id matches that parent Id.
Hope that helps, Jade