Syntax
RAND([N])
Purpose
The RAND([N]) function returns a random floating-point number in the range [0, 1.0). You can use the expression FLOOR(I + RAND() * (j - i)) to generate a random integer in the range [i, j).
If you do not specify the N parameter, the random seed is initialized before execution. After initialization, RAND() generates random numbers based on this seed, resulting in a different sequence of random numbers each time it is executed.
If you specify the N parameter, it is used as the random seed to generate random numbers. The behavior depends on whether N is a constant or a variable:
If
Nis a constant, it is used as the random seed before execution. After initialization,RAND(N)generates random numbers based on this seed. The sameNvalue will produce the same sequence of random numbers.If
Nis a variable (such as a column value), it is used as the random seed each time it is executed. The sameNvalue will produce the same random number.
In addition to being used in SELECT statements, RAND([N]) can also appear in WHERE, ORDER BY, and GROUP BY clauses. It follows the same execution 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
