RAND
Declaration
RAND([N])
Description
The RAND([N]) function accepts 0 or 1 parameter (where N is called the random number seed). It 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 parameter N is not specified, the random seed is initialized before execution, and RAND() generates random numbers based on this seed. Therefore, RAND() generates a different sequence of random numbers each time.
If the parameter N is specified, it serves as the random number seed. The behavior depends on whether N is a constant or a variable:
-
If
Nis a constant, it is initialized as the random seed before execution.RAND(N)then 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 the function is executed. The sameNvalue will generate 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, following the same execution rules. 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
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 (0.001 sec)