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';
Community
  • 1
  • 1
AndrewFerrara
  • 2,383
  • 8
  • 30
  • 45

3 Answers3

52

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

$query = 'SELECT * FROM gameids ORDER BY RAND() LIMIT 1';
Marwelln
  • 28,492
  • 21
  • 93
  • 117
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
Alan Whitelaw
  • 16,171
  • 9
  • 34
  • 51
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.

ludesign
  • 1,353
  • 7
  • 12
  • 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? – AndrewFerrara Feb 09 '11 at 21:13
  • Is it innnoDB or MyISAM? What type is your primary key? Do you have columns with numeric data only? – ludesign Feb 09 '11 at 21:13