Monday, June 16, 2014

MySQL random integers

This is not a new feature by any means but it is a question I have happen to see pop up every now and then. So a quick example is following.

To generate a random integer within MySQL you can use the Floor and Rand functions. The MySQL manual documents this here: http://dev.mysql.com/doc/refman/5.5/en/mathematical-functions.html#function_rand

"To obtain a random integer R in the range i <= R < j, use the expression FLOOR(i + RAND() * (j – i))"

So to give an example:

> SET @I = 3; # lower range
> SET @J = 43 - @I; # max range minus lower range

> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G
*************************** 1. row ***************************
lottery_numbers: 4
1 row in set (0.00 sec)
> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G
*************************** 1. row ***************************
lottery_numbers: 8
1 row in set (0.00 sec
> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G
*************************** 1. row ***************************
lottery_numbers: 15
1 row in set (0.00 sec
> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G
*************************** 1. row ***************************
lottery_numbers: 16
1 row in set (0.00 sec
> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G
*************************** 1. row ***************************
lottery_numbers: 23
1 row in set (0.00 sec
> SELECT FLOOR( @I + (RAND() * @J )) as lottery_numbers\G
*************************** 1. row ***************************
lottery_numbers: 42
1 row in set (0.00 sec

No comments:

Post a Comment

@AnotherMySQLDBA