Owen Abbott4,770 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