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!

Happy New Year!

I’m a bit late on this one, approved but I just wanted to say Happy New Year to anyone who comes by the blog (which oddly appears to pull in most of its new traffic through a random tip about Notepad++).

The year is going great for me so far and I hope it’s going well for you too!

Go out and make this the best year of your life so far! Even if there is a bunch of competition to earn that title (meaning that you’ve had some pretty spectacular years), approved just think back on your worst year. It had some competition too, didn’t it? See… setting records in your life is totally do-able.

Seize 2009! :D