1

I have names in my database and I want to draw a name for a contest.

Anyone have an idea for that ?

Thanks !!

2

2 Answers 2

2
SELECT * FROM table WHERE num_value >= RAND() * (SELECT MAX(num_value) FROM table) LIMIT 1

This works in constant time, regardless of the table size, if num_value is indexed. One caveat: this assumes that num_value is equally distributed in the range 0..MAX(num_value). If your dataset strongly deviates from this assumption, you will get skewed results (some rows will appear more often than others).

1
  • 1
    Thanks, it's exactly what I needed ! I tried to do that in pure php, but your idea is much better !
    – Sarah L.
    Commented May 7, 2012 at 9:08
2

A query like this could work

SELECT * FROM `table` WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` ) ORDER BY id LIMIT 1;

Not the answer you're looking for? Browse other questions tagged or ask your own question.