Given this query, which column or columns should be indexed to optimize query performance?
SELECT *
FROM `activities`
WHERE (user_id = 90000 AND activity_type_id IN(300,400,808,9494))
ORDER BY created_at DESC
LIMIT 70
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
In general, the selection filters can use indexes on
user_idoractivity_type_idor both (in either order).The ordering operation might be able to use a filter on
created_at.It is likely that for this query, a composite index on
(user_id, activity_type_id)would give the best result, assuming that MySQL can actually make use of it. Failing that, it is likely to be better to indexuser_idthanactivity_type_idbecause it is likely to provide better selectivity. One reason for thinking that is that there would be 4 subsections of the index to scan if it uses an index onactivity_type_id, compared with just one subsection to scan if it uses an index onuser_idalone.Trying to rely on an index for the sort order is likely to mean a full table scan, so it is less likely to be beneficial. I would not create an index on
created_atto support this query; there might be other queries where it would be beneficial.