I am implementing a roulette wheel selection, and I would like to keep as much code as possible in SQL. My attempt has yielded the query below. $1 is a random variable of the same range as weight I send to the SQL code (it was not clear how to make random() be called only once). Weight is the size of the row's slot on the wheel. random() is a SQLITE function that returns a random number. Here is the query in full:
SELECT id
FROM items
WHERE weight >= $1
ORDER BY random()
LIMIT 1
My question is, is this still the roulette wheel? The basic algorithm would require the summation of all weights, then picking a random value of the range 0..sum -- this would determine which row was selected. Instead this routine first filters all rows that meet one random number, then scrambles their order and picks the first.
One subtle change is the use of $1 instead of a second call to random(). This may make the routine more fair, but I'm not certain it does -- it would mean that each row was given it's own chance to be filtered or not.
So, I guess I am asking how much does this mirror roulette wheel, since it obviously follows different steps. But does it mirror the results?