Below is the structure of a table:-
Article: ID, Title, Desc, PublishedDateTime, ViewsCount, Published
Primary Key: ID
Query Used:
Select Title FROM Article ORDER By ViewsCount DESC, PublishedDateTime ASC
As you can see that I am mixing ASC and DESC & according to MySQL Order By optimization, indexes will not be used.
I have thought to use a composite index using the ViewsCount and PublishedDateTime. Do you recommend to use 2 different keys instead of using composite index. But then I have read that composite index is better than using 2 different keys (if both fields are going to be used).
Some more information shared:
The table contains more than 550K+ records and also I am having big trouble in adding and deleting indexes for test purpose. What do you guys recommend ? Should I test on a small sample ?
Below are some more insights:
Indexes Used:
1) ViewsCount
2) PublishedDateTime.
3) ViewsCount & PublishedDateTime (named as ViewsDate_Index )
A) EXPLAIN Query mixing ASC and DESC:
EXPLAIN SELECT title FROM `article` ORDER BY ViewsCount DESC , PublishedDateTime ASC LIMIT 0 , 20
====+===============+=========+======+===============+=====+=========+======+========+================+
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 | SIMPLE | article | ALL | NULL | NULL| NULL | NULL | 550116 | Using filesort
====+===============+=========+======+===============+=====+=========+======+========+================+
B) EXPLAIN Query using the same sorting order:
EXPLAIN SELECT title FROM `article` ORDER BY ViewsCount DESC , PublishedDateTime DESC LIMIT 0 , 20
====+===============+=========+=======+===============+=================+=========+=============+========+================+
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 | SIMPLE | article | index | NULL | ViewsDate_Index | 16 | NULL | 550116 |
====+===============+=========+=======+===============+=================+=========+=============+========+================+
You can see that if ViewsCount and PublishedDateTime are in 2 same sorting order then it uses the ViewsDate_Index index. One thing that I found strange was that possible_keys is NULL and still it selects an index. Can someone explain the reason for this.
Also any tips on adding indexes on this table because it takes alot of time to add a new index. Any workaround or help in this regarding will be appreciated.