Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MySQL: Index invalid when selecting by a random id

There’s a table:

`id` INT(10) NOT NULL AUTO_INCREMENT,
`status` TINYINT(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`) USING BTREE,

When I processing the flowing statement (There’s more than 1000 records in this table), a table scan is processed. Why primary key index does not work?

SELECT * FROM t_test WHERE id = FLOOR(1 + RAND() * 1000)

enter image description here
And sometimes there 2 different results, why would this happen?
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

index invalid when mysql select by random id and sometimes return tow different values

>Solution :

When doing this:

WITH abc AS (SELECT FLOOR(1 + RAND() * 1000) as  R)
SELECT * FROM t_test WHERE id = (SELECT R FROM abc);

You might expect that the CTE only returns one record, and the index can be used.

but when adding EXPLAIN it shows UNCACHEABLE:

id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 PRIMARY t_test null ALL null null null null 1024 100.00 Using where
2 UNCACHEABLE SUBQUERY null system null null null null 1 100.00
3 DERIVED null null null null null null null null null No tables used
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading