MySQL get a random value between two values

mahabub.devs3
Mahabubur Rahman
Published on Sep, 17 2024 1 min read 0 comments
image

Actually, ROUND((RAND() * (max-min))+min) is the best way in MySQL to do what you'd like. It is also the best way in ActionScript, JavaScript, and Python. 

So for example you want an integer between 1 and 9:

  • 9 - 1 + 1 gives you 9
  • RAND() * 9 gives you a float between 0 (inclusive) and 9 (excluded)
  • FLOOR(...) converts the previous result to an integer between 0 and 8 (both inclusive)
  • Adding 1 to previous result gives you an integer between 1 and 9 (both inclusive)

 

 

 

0 Comments