SELECT foo FROM bar
WHERE id >= (abs(random()) % (SELECT max(id) FROM bar))
LIMIT 1;
I saw this in another answer as an alternative to ORDER BY random(). I need to make sure id would always be greater than zero. Do I have to change >= to >?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Since
x % yreturns 0 whenxis a multiple ofy, the answer is “Yes, your expression could return 0”.So, if
idmust be greater than 0, you need to use>rather than>=. Of course, if the modulo operator didn’t return 0, you could still use>instead of>=and you’d get the same effect.