Quick Tip: Generate Random Numbers in a MySQL Query

Noticed a dearth of Google articles about this so I figured I’d post my solution…

If you need to generate a random number inside of a MySQL query (which is useful for making fake test-data), there you can do it as follows:

SELECT floor(rand() * 10) as randNum;

Which would generate a random integer from 0 to 9 inclusive. Just change the 10 to the number one higher than you want to generate. The important part is just the “floor(rand() * THE_EXCLUSIVE_UPPER_BOUND)”.

The full explanation is that rand() will generate a random floating point number that is greater than or equal to 0 but less than 1. After you multiply that number by your upper-bound, sales floor() gets rid of everything after the decimal point.

Hope that helps someone!

6 thoughts on “Quick Tip: Generate Random Numbers in a MySQL Query

Leave a Reply

Your email address will not be published.