Declaration
RAND([N])
Description
The RAND([N]) function accepts 0 or 1 parameter (N, which is called the random number seed), and returns a random floating-point number in the range [0,1.0). To obtain a random integer in the range [i, j), you can use the expression FLOOR(I + RAND() * (j - i)).
If the N parameter is not specified, a random seed is used for initialization before execution. Subsequently, RAND() generates random numbers based on this initial value, so RAND() produces a different sequence of random numbers each time.
If the N parameter is specified, it will be used as a random number seed to generate random numbers. Depending on whether N is a constant, there are the following two cases:
If
Nis a constant, it is initialized as a random seed before execution. Subsequently,RAND(N)generates random numbers based on this initial value. The sameNvalue will produce the same sequence of random numbers.If
Nis a variable (for example,Nis a column value), thenNwill be used as a random number seed to generate random numbers on each execution. The sameNvalue will generate the same random numbers.
In addition to being used in the SELECT statement, RAND([N]) can also be used in WHERE, ORDER BY, and GROUP BY statements. Its execution follows the same rules as described above. For example, to randomly sort a table, you can use SELECT FROM T1 ORDER BY RAND(). To randomly sample 100 rows from a table, you can use SELECT FROM T1 ORDER BY RAND() LIMIT 100.
Examples
obclient> SELECT A, B, RAND() FROM T3;
+------+------+---------------------+
| A | B | RAND() |
+------+------+---------------------+
| 1 | 1 | 0.641815407799385 |
| 2 | 2 | 0.16825051248841966 |
| 3 | 3 | 0.9158063697775886 |
+------+------+---------------------+
3 rows in set