MySQL Forums
Forum List  »  Newbie

Re: Why can't MySQL use a range over a Clustered Primary Key
Posted by: Paul Dugdale
Date: January 20, 2022 11:56AM

Thanks very much!

I'm also on MySQL 8.0.27. Here are the explains of the two queries:

mysql> EXPLAIN SELECT * FROM device_data WHERE device_id IN (1) AND timestamp <= CURDATE() - INTERVAL 1 YEAR;
+----+-------------+-------------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| 1 | SIMPLE | device_data | NULL | range | PRIMARY | PRIMARY | 9 | NULL | 1 | 100.00 | Using where |
+----+-------------+-------------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)


mysql> EXPLAIN SELECT * FROM device_data WHERE device_id IN (SELECT device_id FROM device_data GROUP BY device_id) AND timestamp <= CURDATE() - INTERVAL 1 YEAR;
+----+-------------+-------------+------------+------+---------------+---------+---------+------------------------------------------------+------+----------+--------------------------------------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+-------------+------------+------+---------------+---------+---------+------------------------------------------------+------+----------+--------------------------------------+
| 1 | SIMPLE | device_data | NULL | ALL | PRIMARY | NULL | NULL | NULL | 1 | 100.00 | Using where |
| 1 | SIMPLE | device_data | NULL | ref | PRIMARY | PRIMARY | 4 | controlworks_development.device_data.device_id | 1 | 100.00 | Using index; FirstMatch(device_data) |
+----+-------------+-------------+------------+------+---------------+---------+---------+------------------------------------------------+------+----------+--------------------------------------+
2 rows in set, 1 warning (0.00 sec)


I would have expected MySQL could use the Primary Key as an index in the second query, since the data is structured correctly to do that?

Options: ReplyQuote


Subject
Written By
Posted
Re: Why can't MySQL use a range over a Clustered Primary Key
January 20, 2022 11:56AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.