13

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

Is this the correct way to do this?

$query = 'SELECT * FROM gameids ORDER BY timestamp RAND LIMIT 1';
0

3 Answers 3

52

Incorrect. You cant order by a column (afaik) if you want it to randomize.

$query = 'SELECT * FROM gameids ORDER BY RAND() LIMIT 1';
3
  • Won't work with rand - rand() is a function. Commented Feb 8, 2011 at 21:51
  • @Piskvor: I rewrote my answer.
    – Marwelln
    Commented Feb 8, 2011 at 21:52
  • +1 for being about 30 seconds faster at typing! Commented Feb 8, 2011 at 21:53
7

You don't need to tell it which column to randomise, but you do need () after RAND because it is a function.

SELECT
  * 
FROM
  gameids 
ORDER BY 
  RAND()
LIMIT 1
2

RAND is a function and its not effective in big tables, because it does not use indexes.

$query = 'SELECT * FROM gameids ORDER BY RAND() LIMIT 1';

One possible solution is to add column called random and on every record generate random number for it, then when you are querying the database, order by this column and you'll get pseudo-random but this time using the indexes.

$query = 'SELECT * FROM gameids ORDER BY timestamp, random LIMIT 1';

Edit: You can also make RAND() more "flexible" by applying some expression like this RAND() * MAX(numeric_column_name)

If you are interested in optimizations, take a look at this blog post: http://jan.kneschke.de/projects/mysql/order-by-rand/

@Marwelln is correct.

2
  • Well this is a very very big database is there a way to get the total rows, and then generate a random number to sort by? Commented Feb 9, 2011 at 21:13
  • Is it innnoDB or MyISAM? What type is your primary key? Do you have columns with numeric data only?
    – ludesign
    Commented Feb 9, 2011 at 21:13

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