Environment: MySql, Rails 3.0.7
In my user table I have a ‘last_activity_date’ column which is kept up to date using various after_save hooks scattered throughout the app.
I currently have the following named scope:
scope :active, lambda { where('last_activity_date >= ?', 1.month.ago) }
which is used very frequently. It had not seemed worth indexing that column given it’s lack of selectivity and because it is updated fairly frequently (daily for some users, very seldom for others).
As the number of users grows, queries using the ‘active’ scope are taking longer and longer, though. Will indexing the ‘last_activity_date’ column be worth it in the long run?
If the queries you have look like your comment:
then definitely, yes, the performance of these queries will greatly improve with a simple index on
last_activity_dateI guess that
users.idis thePRIMARY KEYof the table, so there is already an index on it.When you don’t have an index, the query has to scan the whole
userstable, to check which rows satisfy the conditionlast_activity_date >= 1 month ago. With a small numbers of users that goes unnoticable. With thousands (or millions) of users, it will be real slow.