Assume I have a very large table X and I want to run below SQL.
select * from table X where type='X1234' order by time;
type is not unique and indexed ( with high cardinality), and there are very few rows in one type ( assume 1 - 5 ). Data size of each row is about 50 byte to 50K byte
Do I still need index for time column?
I think although the table is very large, but "where" clause should be executed before "order by", that will result in a small dataset and no index is needed for column time. Am I right?
Thanks!
Update:
I have tested with composite index ( type, time ), and single index ( type ), the report explain shows as below.
Composite index
+----+-------------+---------+------------+------+-----------
| id |type |ref | rows | filtered | Extra |
+----+-------------+---------+------------+------+----------+
| 1 |ref |const | 3 | 100.00 | Using index condition |
+----+-------------+---------+------------+------+----------+
Single index
+---------+------------+------+---------------+------------+---------+------+
| id |type |ref | rows | filtered | Extra |
+----+-------------+---------+------------+------+---------------+----------+
| 1 |ref |const | 3 | 100.00 | Using index condition; Using filesort |
+----+-------------+---------+------------+------+---------------+----------+
There is no noticeable difference in execution time. It is likely the dataset is small and the filesort operation was entirely performed in buffer cache, so it is still very fast.
In case the dataset become larger, then using composite index should be a good idea.
timewill not affect at all - only one index can be used in query type You show. Ever resultset is large (but in this case composite index by (type,time) will improve). The main direction in optimization is to replace asterisk with the list of columns You really need - maybe it's possible to create covering index. – Akina May 30 '18 at 16:04EXPLAIN PLANor whatever the syntax is for your RDBMS (which you didn't tag - could you do this?) for both scenarios! – Vérace May 30 '18 at 17:19