We have a query which goes like this:
select *
from foo
where some_fk_id = <value>
and modified_date > 'date1'
and modified_date < 'date2'
order by modified_date desc;
Do I need to create a composite index for some_fk_id and modified_date in the above scenario?
You don’t need a composite index, but satisfying the
some_fk_idandmodified_datewhere clause could be done with indexes alone (i.e. very quickly) if you do.The best thing to do is to see the query plan and to profile.
You can see the query plan using
EXPLAIN:Try it both with and without a composite index and see what plan it comes up with. The worst possible thing that can happen is a
filesort–try to avoid those if you need to be speedy.Most importantly, run time trials with the queries, data, and hardware you will actually use. It may be in your particular case that the space taken up by a composite index will slow you down more than just searching through the entries. For example, if some_fk_id has very high selectivity in the table, the second-level index may not be necessary.