Random Numbers RAND

suggest change

Generate a random number

To generate a pseudorandom floating point number between 0 and 1, use the RAND() function

Suppose you have the following query

SELECT i, RAND() FROM t;

This will return something like this

i | RAND() | —— | —— | 1 | 0.6191438870682 | 2 | 0.93845168309142 | 3 | 0.83482678498591 |

Random Number in a range

To generate a random number in the range a <= n <= b, you can use the following formula

FLOOR(a + RAND() * (b - a + 1))

For example, this will generate a random number between 7 and 12

SELECT FLOOR(7 + (RAND() * 6));

A simple way to randomly return the rows in a table:

SELECT * FROM tbl ORDER BY RAND();

These are pseudorandom numbers.

The pseudorandom number generator in MySQL is not cryptographically secure. That is, if you use MySQL to generate random numbers to be used as secrets, a determined adversary who knows you used MySQL will be able to guess your secrets more easily than you might believe.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents