Monday, April 6, 2009

MySQL random sample

If you need to select a random sample of rows from a MySQL result set use the RAND function to randomly order your results, and LIMIT to limit the number of records. For instance, if you need to select 3 winners from a pool of entries stored in a table for a certain time period you could use the following:
SELECT * FROM entries 
WHERE entry_date < '2009-04-01'
AND entry_date >= '2009-01-01'
ORDER BY RAND()
LIMIT 3

This would return 3 random entries from the result set.

No comments:

Post a Comment