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?

Community
  • 1
  • 1
Aaron
  • 1,956
  • 5
  • 34
  • 56
  • This is biased depending of the holes but I don't see how this could select a non existing row. – Denys Séguret Jun 22 '12 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: http://stackoverflow.com/questions/10677767/fastest-random-selection-where-column-x-is-y-null/10677869#10677869 – Spudley Jun 22 '12 at 19:32

4 Answers4

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

McIntosh
  • 2,051
  • 1
  • 22
  • 34
  • Does this take into account deleted rows? – Aaron Jun 22 '12 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 `DELETE`ing the row completely you need to add a `WHERE deleted=0` to your statement – McIntosh Jun 22 '12 at 12:44
4
SELECT * FROM table ORDER BY RAND() LIMIT 1
sp00m
  • 47,968
  • 31
  • 142
  • 252
1
SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;

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

Darren
  • 68,902
  • 24
  • 138
  • 144
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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758