9

Possible Duplicate:
quick selection of a random row from a large table in mysql

I have seen random rows pulled using queries like this, which are quite inefficient for large data sets.

SELECT id FROM table ORDER BY RANDOM() LIMIT 1

I have also seen various other RDBMS-specific solutions that don't work with MySQL.

The best thing I can think of doing off-hand is using two queries and doing something like this.

  1. Get the number of rows in the table. MyISAM tables store the row count so this is very fast.
  2. Calculate a random number between 0 and rowcount - 1.
  3. Select a row ordered by primary key, with a LIMIT randnum, 1

Here's the SQL:

SELECT COUNT(*) FROM table;
SELECT id FROM table LIMIT randnum, 1;

Does anyone have a better idea?

Community
  • 1
  • 1
David
  • 7,487
  • 6
  • 32
  • 25

0 Answers0