NYCPHP Meetup

NYPHP.org

[nycphp-talk] Random record from MySQL

Ophir Prusak lists at prusak.com
Thu Mar 11 12:52:17 EST 2004


I hear what you're saying, but I'm still not convinced.

Any select query with an ORDER BY clause requires the database to do 
some sorting before returning results.

I did a quick Google search and found this thread on the subject:
http://lists.mysql.com/mysql/161338

The short answer is that if you're doing this for a table with a very 
large number of rows, there are more efficient ways than ORDER BY RAND().
Read the above thread for details.

Ophir


David Sklar wrote:

> 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
>
>
>
> _______________________________________________
> talk mailing list
> talk at lists.nyphp.org
> http://lists.nyphp.org/mailman/listinfo/talk




More information about the talk mailing list