Generating Random Numbers
Problem
You need a source of random numbers.
Solution
Invoke MySQL’s RAND( )
function.
Discussion
MySQL has a RAND( )
function that can be invoked to produce
random numbers between 0 and 1:
mysql> SELECT RAND( ), RAND( ), RAND( );
+------------------+------------------+------------------+
| RAND( ) | RAND( ) | RAND( ) |
+------------------+------------------+------------------+
| 0.31466114177803 | 0.89354679723601 | 0.52375059157959 |
+------------------+------------------+------------------+
When invoked with an integer argument, RAND( )
uses that value to seed the random number generator. Each time you
seed the generator with a given value, RAND( )
will produce a repeatable series of numbers:
mysql>SELECT RAND(1), RAND( ), RAND( );
+------------------+------------------+------------------+ | RAND(1) | RAND( ) | RAND( ) | +------------------+------------------+------------------+ | 0.18109050223705 | 0.75023211143001 | 0.20788908117254 | +------------------+------------------+------------------+ mysql>SELECT RAND(20000000), RAND( ), RAND( );
+------------------+-------------------+------------------+ | RAND(20000000) | RAND( ) | RAND( ) | +------------------+-------------------+------------------+ | 0.24628307879556 | 0.020315642487552 | 0.36272900678472 | +------------------+-------------------+------------------+ mysql>SELECT RAND(1), RAND( ), RAND( );
+------------------+------------------+------------------+ | RAND(1) | RAND( ) | RAND( ) | +------------------+------------------+------------------+ ...
Get MySQL Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.