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.
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.
For selecting multiple random rows from a given table (say 'words'), our team came up with this beauty:
Add a column containing a calculated random value to each row, and use that in the ordering clause, limiting to one result upon selection. This works out faster than having the table scan that
ORDER BY RANDOM()
causes.Update: You still need to calculate some random value prior to issuing the
SELECT
statement upon retrieval, of course, e.g.I'm a bit new to SQL but how about generating a random number in PHP and using
this doesn't solve the problem with holes in the table.
But here's a twist on lassevks suggestion:
Use mysql_num_rows() in PHP create a random number based on the above result:
On a side note just how slow is
SELECT * FROM the_table
:Creating a random number based on
mysql_num_rows()
and then moving the data pointer to that pointmysql_data_seek()
. Just how slow will this be on large tables with say a million rows?Take a look at this link by Jan Kneschke or this SO answer as they both discuss the same question. The SO answer goes over various options also and has some good suggestions depending on your needs. Jan goes over all the various options and the performance characteristics of each. He ends up with the following for the most optimized method by which to do this within a MySQL select:
HTH,
-Dipin
SELECT DISTINCT * FROM yourTable WHERE 4 = 4 LIMIT 1;
Quick and dirty method:
The complexity of the first query is O(1) for MyISAM tables.
The second query accompanies a table full scan. Complexity = O(n)
Dirty and quick method:
Keep a separate table for this purpose only. You should also insert the same rows to this table whenever inserting to the original table. Assumption: No DELETEs.
If DELETEs are allowed,
The overall complexity is O(1).