14
Jan/091
Jan/091
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), 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, floor() gets rid of everything after the decimal point.
Hope that helps someone!
Comments (1)
Trackbacks (0) ( subscribe to comments on this post )
Leave a comment
No trackbacks yet.
8:33 am on August 24th, 2009
Thx…
its very useful