I have a table with two columns, batch_id and study_id. There are indexes on both columns. I want to get a random row back from MySQL.
I originally wrote:
SELECT * FROM alt_join_batch_study ORDER BY RAND() LIMIT 1
but that proved slow. Here's the explain.
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE alt_join_batch_study ALL NULL NULL NULL NULL 172235 Using temporary; Using filesort
I was surprised it wasn't using any indexes. I tried this:
SELECT batch_id, study_id FROM alt_join_batch_study ORDER BY RAND() LIMIT 1
and Lo! it was faster. And the explain shows the use of the index.
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE alt_join_batch_study index NULL study_id 4 NULL 172235 Using index; Using temporary; Using filesort
Why wouldn't MySQL find the index when I do SELECT * ...?