Reputation: 1005
I'm using a Mac OSX version 10.8 and Rails 3.2.14
Here is the link: http://ruby.railstutorial.org/chapters/following-users?version=3.2#sec-a_problem_with_the_data_model
Scroll down to Listing 11.1.
Question: What is the point of adding indices to the relationships table?
The relationship table has two columns follower_id (input) and followed_id (output). It sounds like that is all you need to connect user (x) to user (y), why do you need an index. Is it an extra column/field? If not, what is it. And what does it do? Why is it necessary to use it?
Thanks
Upvotes: 0
Views: 53
Reputation: 528
Unless you add an index to a column then the database can't search the column directly. Instead it has to go through each row and then look at the value for that column. If we were talking excel sheets and you wanted to quickly look at all the values in column 'M' you could just keep your eye or finger on that column and scroll down. Imagine instead that you have to start at column 'A' and then scroll right to read column 'M'. Rinse and repeat 1,000 times and you're adding a lot if time to your query.
The composite index on both fields together prevents a user from following the same person twice. While you should also prevent this in your code it doesn't hurt to duplicate the uniqueness validation in the database because historically speaking databases outlive the application.
Upvotes: 1