2

Possible Duplicate:
How to request a random row in SQL?

Currently Using:

$randomQuery = mysql_fetch_row(mysql_query("SELECT * FROM `table` WHERE `id` >= RAND() * (SELECT MAX(`id`) FROM `table`) LIMIT 1"));

Table Structure:

id:
 2 
 4
 5

I want to make sure it's selecting an existing row. For example, it shouldn't be able to use 1 or 3 in its randomizing function. Is there a way to do this in MySQL?

2
  • This is biased depending of the holes but I don't see how this could select a non existing row. Commented Jun 22, 2012 at 12:02
  • Any solution using RAND() will be slow because it can't do an index. For faster, properly indexed solution, see my answer here: stackoverflow.com/questions/10677767/…
    – Spudley
    Commented Jun 22, 2012 at 19:32

4 Answers 4

8

I think

SELECT * FROM table ORDER BY RAND() LIMIT 1

would do the trick.

See:

http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html#function_rand

2
  • Does this take into account deleted rows?
    – Aaron
    Commented Jun 22, 2012 at 12:04
  • deleted rows - i think - are removed from the storage engine, so they will not be included in the result. If you only have a deleted flag in the row instead of DELETEing the row completely you need to add a WHERE deleted=0 to your statement
    – McIntosh
    Commented Jun 22, 2012 at 12:44
4
SELECT * FROM table ORDER BY RAND() LIMIT 1
1
  • this will work, but will be slow because it won't use an index.
    – Spudley
    Commented Jun 22, 2012 at 19:31
1
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;

http://akinas.com/pages/en/blog/mysql_random_row/

0

Your initial query does take care of the holes as it simply compares the id of a row to the random value you compute and doesn't try to fetch a row having a random id.

Its problem is that it gives you a non uniform probability : Any row following a big hole has a bigger probability of being selected.

That's the reason why it's suggested to use the mysql trick ORDER BY RAND() (see other answers) as the randomization will be quasi uniform.

Not the answer you're looking for? Browse other questions tagged or ask your own question.