NYCPHP Meetup

NYPHP.org

[nycphp-talk] Random record from MySQL

David Sklar sklar at sklar.com
Thu Mar 11 11:19:52 EST 2004


Ophir Prusak wrote:
> 
> I've never seen this solution before. Very simple.
> I wondering though about the efficiency of this solution.
> 
> It seems to me that this assigns a random value to each row and then 
> orders by that row.
> Does the DB do a full table scan using this method?
> 
> If yes, this would be a very inefficient method for very large tables.

It is inefficient if you are retrieving the whole table ordered by 
RAND(), but with the LIMIT clause, the table scan is short-circuited 
after one row is found. So,

SELECT * FROM table ORDER BY RAND()

can be slow if there are a lot of rows in the table, but

SELECT * FROM table ORDER BY RAND() LIMIT 1

is OK.

David






More information about the talk mailing list