What is a fast way to select a random row from a large mysql table?
I\'m working in php, but I\'m interested in any solution even if it\'s in another language.
In my case my table has an id as primary key, auto-increment with no gaps, so I can use COUNT(*)
or MAX(id)
to get the number of rows.
I made this script to test the fastest operation:
logTime();
query("SELECT COUNT(id) FROM tbl");
logTime();
query("SELECT MAX(id) FROM tbl");
logTime();
query("SELECT id FROM tbl ORDER BY id DESC LIMIT 1");
logTime();
The results are:
36.8418693542479 ms
0.241041183472 ms
0.216960906982 ms
Answer with the order method:
SELECT FLOOR(RAND() * (
SELECT id FROM tbl ORDER BY id DESC LIMIT 1
)) n FROM tbl LIMIT 1
...
SELECT * FROM tbl WHERE id = $result;