Below is the table structure: -
Article: ID, Title, Desc, PublishedDateTime, ViewsCount, Published
Primary Key: Identifier
Used query:
Select Title FROM Article ORDER By ViewsCount DESC, PublishedDateTime ASC
As you can see, I am mixing ASC and DESC and according to the optimization of MySQL Order By, indexes will not be used.
I thought of using a composite index using ViewsCount and PublishedDateTime. You recommend using 2 different keys instead of using a composite index. But then I read that a composite index is better than using two different keys (if both fields will be used).
Additional Information:
The table contains more than 550K + records, and there are also big problems with adding and removing indexes for testing purposes. What do you guys recommend? Should I test a small sample?
The following are some additional information:
Indexes Used:
1) ViewsCount
2) PublishedDateTime.
3) ViewsCount and PublishedDateTime (called ViewsDate_Index)
A) EXPLAIN Mixing ASC and DESC queries:
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 sort 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 PublisherDateTime are in the same sort order, then it uses the ViewsDate_Index index. The only thing that seemed strange to me was that possible_keys is NULL, and yet it selects the index. Can someone explain the reason for this.
Also any tips for adding indexes to this table, because adding a new index takes a lot of time. Any workaround or help in this regard would be appreciated.